def OnSetCursor(self, window, nHitTest, wMouseMsg): if nHitTest != win32con.HTSIZE or self.bTracking: return self._obj_.OnSetCursor(window, nHitTest, wMouseMsg) if self.IsHorz(): win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZENS)) else: win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZEWE)) return 1
def control_preview_thread(self, hCamera, topHwnd): """ Function to be executed by a thread in charge of showing the camera preview :param topHwnd: integer number that corresponds to the parent window the stream will be showed in :return: an assertion that the stream was successfully stopped, once the user exits the preview """ user32 = windll.user32 msg = ctypes.wintypes.MSG() pMsg = ctypes.byref(msg) # Create an arror cursor (see below) defaultCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) ret = PxLApi.setPreviewSettings( hCamera, "", PxLApi.WindowsPreview.WS_VISIBLE | PxLApi.WindowsPreview.WS_CHILD, 25, 25, self.stream_width, self.stream_height, topHwnd) # Start the preview (NOTE: camera must be streaming). Keep looping until the previewState is STOPed ret = PxLApi.setPreviewState(hCamera, PxLApi.PreviewState.START) while (PxLApi.PreviewState.START == self.previewState and PxLApi.apiSuccess(ret[0])): if user32.PeekMessageW(pMsg, 0, 0, 0, 1) != 0: # All messages are simpy forwarded onto to other Win32 event handlers. However, we do # set the cursor just to ensure that parent windows resize cursors do not persist within # the preview window win32api.SetCursor(defaultCursor) user32.TranslateMessage(pMsg) user32.DispatchMessageW(pMsg) # User has exited -- Stop the preview ret = PxLApi.setPreviewState(hCamera, PxLApi.PreviewState.STOP) assert PxLApi.apiSuccess(ret[0]), "%i" % ret[0]
def startPycheckerRun(self): self.result = None old = win32api.SetCursor( win32api.LoadCursor(0, win32con.IDC_APPSTARTING)) win32ui.GetApp().AddIdleHandler(self.idleHandler) import _thread _thread.start_new(self.threadPycheckerRun, ())
def __init__(self, host='localhost', password=None): self.client = Client(host=host, password=password, socket_timeout=10) msg_task_bar_restart = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { msg_task_bar_restart: self._on_restart, win32con.WM_DESTROY: self._on_destroy, win32con.WM_COMMAND: self._on_command, self._WM_USER_STOCK_DATA: self._on_data_receive, win32con.WM_USER + 20: self._on_taskbar_notify } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "StockTaskBar" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except win32gui.error, err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise
def __init__(self): restart_message = win32gui.RegisterWindowMessage('TaskBar Created') message_map = {restart_message: self.restart, win32con.WM_DESTROY: self.destroy, win32con.WM_COMMAND: self.command, win32con.WM_USER+20: self.taskbar_notify} wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "Tracker" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except win32gui.error: raise # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "Taskbar Demo", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self.create_icon()
def __init__(self): msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER + 20: self.OnTaskbarNotify, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "PythonTaskbarDemo" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except win32gui.error as err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "Taskbar Demo", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self._DoCreateIcons()
def __init__(self): wx.EvtHandler.__init__(self) msg_TaskbarCreated = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { msg_TaskbarCreated: self.OnTaskbarCreated, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER + 20: self.OnTaskbarNotify } wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "SysTrayIcon" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map classAtom = win32gui.RegisterClass(wc) style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "SysTrayIcon", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self._nid = None self.in_popup = False self.menu = None self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnRightUp) # With wxPython 4, calling <EvtHandler>.Destroy() no longer makes the # instance evaluate to False in boolean comparisons, so we emulate that # functionality self._destroyed = False
def mouse_cursorTypeNameDictionary() -> dict: h = {} for x in util_filterObjectProperties(): try: _ = h[win32api.LoadCursor(0, getattr(win32con, x))] = x except: pass return h
def __init__(self, icon, hover_text, menu_options, on_quit=None, default_menu_index=None, window_class_name = "EnsoTrayWndClass",): self.default_icon = icon self.hover_text = hover_text self.notify_id = None if on_quit: self.on_quit = on_quit self.custom_menu_items = {} self.WM_ONLOAD = win32gui.RegisterWindowMessage("SystrayOnLoad") self.WM_CREATED = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { self.WM_CREATED : self._on_restart, self.WM_ONLOAD: self._on_load, win32con.WM_DESTROY: self._on_destroy, win32con.WM_COMMAND: self._on_command, win32con.WM_USER + 20 : self._on_taskbar_notify, } # Register the Window class. self._window_class = win32gui.WNDCLASS() self._window_class.hInstance = win32api.GetModuleHandle(None) self._window_class.lpszClassName = window_class_name self._window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; self._window_class.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) self._window_class.hbrBackground = win32con.COLOR_WINDOW self._window_class.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: self.class_atom = win32gui.RegisterClass(self._window_class) except win32gui.error as err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise # Create the helper Window style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow( self.class_atom, window_class_name, #Title same as class-name style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, self._window_class.hInstance, None) win32gui.UpdateWindow(self.hwnd) self._create_icons()
def load(): import config for idc_name, curfile in config.CURSOR_LOCATIONS.iteritems(): idc = getattr(win32con, idc_name) assert idc, "invalid idc name" OS_CURSORS[idc] = skwinapi.CopyCursor(win32api.LoadCursor(0, idc)) hcur = skwinapi.LoadCursorFromFileW(curfile) if hcur: skwinapi.SetSystemCursor(hcur, idc) dprint("pass")
def __init__(self, menu_options, program_name='Python Taskbar', window_name=None): self.logger = logging.getLogger("tray") self.cache = {} self._commands = { 'OnMenuOpen': [], 'OnMenuClose': [], 'OnWindowHide': [], 'OnWindowRestore': [] } self.program_name = program_name try: self.console_hwnd = WindowHandle(parent=False, console=True) except NameError: self.console_hwnd = None self._refresh_menu(menu_options) if window_name is None: window_name = program_name #Set up callbacks msg_TaskbarRestart = win32gui.RegisterWindowMessage('TaskbarCreated') message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, TRAY_EVENT: self.OnTaskbarNotify, } #Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = window_name wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. #Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except (win32gui.error, err_info): if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise #Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(wc.lpszClassName, window_name, style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self._set_icon() self.logger.info('Window created.')
def __init__(self): msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarCreated") #定义一个新的窗口消息 message_map = { #建立函数命令字典,用于窗口回调函数的四个参数 msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER+20 : self.OnTaskbarNotify, } self.menu = win32gui.CreatePopupMenu() #产生一个菜单句柄menu win32gui.AppendMenu(self.menu, win32con.MF_STRING, 1023, "显示/隐藏窗口") #给菜单添加子项,1027可以一直下去 win32gui.AppendMenu(self.menu, win32con.MF_STRING, 1024, "设置") win32gui.AppendMenu(self.menu, win32con.MF_STRING, 1025, "退出程序") #win32gui.EnableMenuItem(menu,1023,win32con.MF_GRAYED)#是用菜单句柄,对菜单进行操作 # Register the Window class. self.wc = win32gui.WNDCLASS() #局部变量wc改成窗口类的实例 hinst = self.wc.hInstance = win32api.GetModuleHandle(None) #获得程序模块句柄 self.wc.lpszClassName = ("PythonTaskbarDemo") #窗口类的类名 self.wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW #窗口类的style特征,水平重画和竖直重画 self.wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) self.wc.hbrBackground = win32con.COLOR_WINDOW self.wc.lpfnWndProc = message_map # could also specify a wndproc,给窗口回调函数赋值 '''这里传进去的其实是函数指针,它里面保存的是我们定义的windowproc的入口地址''' # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(self.wc) #用wc将classatom注册为一个窗口类 except win32gui.error and err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow( self.wc.lpszClassName, "Taskbar Demo", style, #创建一个窗口 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) #更新窗口 self._DoCreateIcons() win32gui.PumpMessages()
def __init__( self, icon, hover_text, menu_options, on_quit=None, default_menu_index=None, window_class_name="EnsoTrayWndClass", ): self.default_icon = icon self.hover_text = hover_text self.notify_id = None self._on_quit = None if on_quit: if not callable(on_quit): raise Exception( "SysTrayIcon on_quit parameter must be callable") self._on_quit = on_quit self.custom_menu_items = {} self.WM_ONLOAD = win32gui.RegisterWindowMessage("SystrayOnLoad") self.WM_CREATED = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { self.WM_CREATED: self._on_restart, self.WM_ONLOAD: self._on_load, win32con.WM_DESTROY: self._on_destroy, win32con.WM_COMMAND: self._on_command, win32con.WM_USER + 20: self._on_taskbar_notify, } # Register the Window class. self._window_class = win32gui.WNDCLASS() self._window_class.hInstance = win32api.GetModuleHandle( None) # @UndefinedVariable self._window_class.lpszClassName = window_class_name self._window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW self._window_class.hCursor = win32api.LoadCursor( 0, win32con.IDC_ARROW) # @UndefinedVariable self._window_class.hbrBackground = win32con.COLOR_WINDOW self._window_class.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: self.class_atom = win32gui.RegisterClass(self._window_class) except win32gui.error, err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise
def start_monitor_thread(cb): wc = win32gui.WNDCLASS() wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "TimeChangeMonitor" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = {} #wnd_proc # could also specify a wndproc. try: classAtom = win32gui.RegisterClass(wc) except win32gui.error as err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise thr = threading.Thread(target=monitor_thread, args=(cb, wc), daemon=True) thr.start()
def CreateWindow( self, parent, childCreator, title, id, style=win32con.WS_CHILD | win32con.WS_VISIBLE | afxres.CBRS_LEFT, childCreatorArgs=(), ): assert not ((style & afxres.CBRS_SIZE_FIXED) and (style & afxres.CBRS_SIZE_DYNAMIC)), "Invalid style" self.rectClose = self.rectBorder = self.rectGripper = self.rectTracker = ( 0, 0, 0, 0, ) # save the style self._obj_.dwStyle = style & afxres.CBRS_ALL cursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wndClass = win32ui.RegisterWndClass(win32con.CS_DBLCLKS, cursor, self.brushBkgd.GetSafeHandle(), 0) self._obj_.CreateWindow(wndClass, title, style, (0, 0, 0, 0), parent, id) # Create the child dialog self.dialog = childCreator(*(self, ) + childCreatorArgs) # use the dialog dimensions as default base dimensions assert self.dialog.IsWindow(), ( "The childCreator function %s did not create a window!" % childCreator) rect = self.dialog.GetWindowRect() self.sizeHorz = self.sizeVert = self.sizeFloat = ( rect[2] - rect[0], rect[3] - rect[1], ) self.sizeHorz = self.sizeHorz[ 0], self.sizeHorz[1] + self.cxEdge + self.cxBorder self.sizeVert = self.sizeVert[ 0] + self.cxEdge + self.cxBorder, self.sizeVert[1] self.HookMessages()
def __init__(self, wp, imgfile, menu): # Create window procedure wp.update({ win32con.WM_DESTROY: self.__destroy, win32con.WM_COMMAND: self.command, self.MSG_NOTIFY: self.__notify, }) # Window class wc = win32gui.WNDCLASS() wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = 'TrayIcon' wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = wp # Register window class win32gui.RegisterClass(wc) # Create Window self.hwnd = win32gui.CreateWindow( wc.lpszClassName, '', win32con.WS_OVERLAPPED | win32con.WS_SYSMENU, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, wc.hInstance, None) win32gui.UpdateWindow(self.hwnd) # Create icon self.hicon = win32gui.LoadImage( wc.hInstance, imgfile, win32con.IMAGE_ICON, 0, 0, win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE) # Add icon into task bar flag = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP nid = (self.hwnd, 0, flag, self.MSG_NOTIFY, self.hicon, self.TITLE) win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) # Create popup menu self.menu = win32gui.CreatePopupMenu() for text, item in menu: self.menu = TrayIcon.create_menu(self.menu, item, text) super().__init__()
def __init__(self, netkeeper): msg_TaskbarRestart = win32gui.RegisterWindowMessage("NKService") message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER + 20: self.OnTaskbarNotify, } # 注册窗口类 wndclass = win32gui.WNDCLASS() hinst = wndclass.hInstance = win32api.GetModuleHandle(None) wndclass.lpszClassName = "NetkeeperTrayIcon" wndclass.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wndclass.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wndclass.hbrBackground = win32con.COLOR_WINDOW wndclass.lpfnWndProc = message_map try: classAtom = win32gui.RegisterClass(wndclass) except win32gui.error, err_info: if err_info.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise
def __init__(self): msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarOlustur"); message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER+20 : self.OnTaskbarNotify, } wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "murat" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = win32api.LoadCursor( 0, win32con.IDC_ARROW ) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map try: classAtom = win32gui.RegisterClass(wc) except win32gui.error, err_info: if err_info.winerror!=winerror.ERROR_CLASS_ALREADY_EXISTS: raise
def __init__(self): msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarOlustur"); message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER+20 : self.OnTaskbarNotify, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "dolarTray" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = win32api.LoadCursor( 0, win32con.IDC_ARROW ) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except win32gui.error, err_info: if err_info.winerror!=winerror.ERROR_CLASS_ALREADY_EXISTS: raise
def setMousePassive(self, x, y): drawFlag = 0 self.movePointX = x # 记录鼠标X坐标 self.movePointY = y # 记录鼠标Y坐标 if self.size == None : return drawFlag if self.movePointX < self.size.x or self.movePointX > self.size.w + self.size.x : if self.mouseChange == True: self.mouseChange = self.mouseChangeLast = False win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_ARROW)) drawFlag = 1 return drawFlag if self.movePointY < self.size.y or self.movePointY > self.size.y + self.size.h : if self.mouseChange == True: self.mouseChange = self.mouseChangeLast = False win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_ARROW)) drawFlag = 1 return drawFlag pointX = (self.movePointX - self.size.x) / self.size.w if pointX > self.x1 - self.margin and pointX < self.x1 + self.margin : # 左侧调整鼠标变化 win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZEWE)) self.mouseChange = True elif pointX > self.x2 - self.margin and pointX < self.x2 + self.margin : # 右侧调整鼠标变化 win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZEWE)) self.mouseChange = True elif pointX > self.x1 + self.margin and pointX < self.x2 - self.margin : # 整体拖动鼠标变化 win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_ARROW)) self.mouseChange = True else: win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_ARROW)) # 鼠标还原 self.mouseChange = False if self.mouseChangeLast != self.mouseChange : self.mouseChangeLast = self.mouseChange drawFlag = 1 return drawFlag
def __init__(self): self.code = "TabletOrderingYD" self.name = "平板点餐服务YD" # 获取编程环境下的代码路径 # self.path = os.path.abspath(os.path.dirname(__file__)) # 获取打包后的可执行文件路径 self.path = os.path.dirname(sys.executable) # 获取配置参数 config = configparser.ConfigParser() confFile = os.path.join(self.path, "wx.conf") if os.path.exists(confFile): config.read(confFile, encoding="utf-8") self.WXPort = config.getint("client", "WXPort") if self.WXPort == 0 or self.WXPort == None: self.WXPort = 8009 else: self.WXPort = 8009 self.logFile = os.path.join(self.path, "wxlog.log") # 创建日志对象 self.logger = self._getLogger() msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarCreated") message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_CLOSE: self.OnClose, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER + 20: self.OnTaskbarNotify, 1280: self.OnPostMessage, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = self.code wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except Exception as e: self.logger.error(str(e)) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(wc.lpszClassName, self.name, style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self._DoCreateIcons() # 获取启动WX窗口的程序句柄 self._interHandle = 0 if len(sys.argv) > 1: if sys.argv[1].isdigit(): if self._interHandle == 0 and int(sys.argv[1]) > 0: self._interHandle = int(sys.argv[1]) # 初始化登录标志 self._loginFlag = 0 # 创建socket server线程 if self._interHandle > 0: # 通知接口程序WX的窗口句柄 windll.user32.PostMessageW(self._interHandle, 1280, 0, self.hwnd) # 创建线程共享数据队列 self.messageQ = Queue() try: tSocket = Thread(target=self.OnSocket, args=(self.WXPort, self.messageQ, self._interHandle, )) tSocket.daemon = True tSocket.start() except Exception as e: self.logger.error("启动进程Err:" + str(e))
def run(self): self.__mode = TrayThermostat.Automatic self.__connected = False msg_TaskbarRestart = win32gui.RegisterWindowMessage("TaskbarCreated"); message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER+20 : self.OnTaskbarNotify, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "HTPCThermostat" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = win32api.LoadCursor( 0, win32con.IDC_ARROW ) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. # Don't blow up if class already registered to make testing easier try: classAtom = win32gui.RegisterClass(wc) except win32gui.error as err_info: if err_info.winerror!=winerror.ERROR_CLASS_ALREADY_EXISTS: raise # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow( wc.lpszClassName, "HTPC Thermostat Taskbar", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self._DoCreateIcons() # There must be an event to wait for even if its not used. Otherwise # MsgWaitForMultipleObjects will just return immediately. last_poll = 0 while True: # If we're here, then we're not connected. self.__connected = False # MsgWaitForMultiple objects will miss events between calls if win32gui.PumpWaitingMessages(): return try: # Wait 0.2 seconds for the device (so as not to delay win32 Message Loop) with self.__w32hid.device(timeout=0.2) as vs: # If we made it here, then we're connected self.__connected = True # On the first reading always set the switch state changes = False while True: # MsgWaitForMultiple objects will miss events between calls if win32gui.PumpWaitingMessages(): return # Now we wait . . . if self.__wait_msg_pump(): return if (time.time() * 1000) - last_poll >= 2000: last_poll = time.time() * 1000 # Set the voltage switch based on our current mode if self.__mode == TrayThermostat.Automatic: # Send the sensor reading to the thermostat for the voltage switch if not vs[self.__thermostat.mode(self.__sensor.reading(), changes)](): # If no command sent, check to ensure still connected if not self.__w32hid.attached(): break # From now on, only set switch state on changes changes = True elif self.__mode == TrayThermostat.V12: vs.set12v() changes = False elif self.__mode == TrayThermostat.V5: vs.set5v() changes = False elif self.__mode == TrayThermostat.V0: vs.set0v() changes = False except: log.exception("Terminated HID connection") # Now we wait 300 milliseconds for GUI messages if self.__wait_msg_pump(timeout=300): return
def on_click(x, y, button, pressed): print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y))) win32api.LoadCursor(None, win32con.IDC_NO) if not pressed: # Stop listener return False
class LeagueOfAngels: def __init__(self, auto=True, screenshot=None, mode=Mode.Desktop): self.hwnd = None self.gamepos = None self.mode = mode self.screenshot = screenshot if screenshot is None: self.get_game_hwnd(auto=auto) self.get_game_bbox() else: self.gamepos = 0, 0, screenshot.size[0], screenshot.size[1] self.resources = {} def get_game_hwnd(self, auto=True): windows = [] def foreach_window(hwnd, lparam): nonlocal windows if win32gui.IsWindowVisible(hwnd): window_text = win32gui.GetWindowText(hwnd) if "League of Angels" in window_text: windows.append((hwnd, window_text)) logging.debug("Found game window hwnd: {0} title: {1}".format(hwnd, window_text)) return True win32gui.EnumWindows(foreach_window, None) if len(windows) == 0: logging.error("Failed to find game window.") raise Exception("Failed to find game window.") elif len(windows) > 1 and not auto: print("Found {0} possible game windows.".format(len(windows))) for i in range(1, len(windows) + 1): print("{0}: {1}".format(i, windows[i-1][1])) windownum = input("Enter the number for the window you which to use [1]: ") if windownum == "": windownum = 0 else: windownum = int(windownum) - 1 logging.info("Using window {0}".format(windows[windownum][1])) self.hwnd = windows[windownum][0] else: self.hwnd = windows[0][0] if self.mode == Mode.Desktop: self.focus() def focus(self): # Make game window active. win32gui.SetWindowPos(self.hwnd, win32con.HWND_TOP, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE + win32con.SWP_SHOWWINDOW) win32gui.SetForegroundWindow(self.hwnd) win32gui.ShowWindow(self.hwnd, win32con.SW_RESTORE) time.sleep(0.250) def capture_screenshot(self): im = None if self.mode == Mode.Window: left, top, right, bot = win32gui.GetClientRect(self.hwnd) w = right - left h = bot - top hwnddc = win32gui.GetWindowDC(self.hwnd) mfcdc = win32ui.CreateDCFromHandle(hwnddc) savedc = mfcdc.CreateCompatibleDC() savebitmap = win32ui.CreateBitmap() savebitmap.CreateCompatibleBitmap(mfcdc, w, h) savedc.SelectObject(savebitmap) # Change the line below depending on whether you want the whole window # or just the client area. result = windll.user32.PrintWindow(self.hwnd, savedc.GetSafeHdc(), 1) logging.debug("PrintWindow result: {}".format(result)) if result == 1: bmpinfo = savebitmap.GetInfo() logging.debug(bmpinfo) bmpstr = savebitmap.GetBitmapBits(True) im = Image.frombuffer( 'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) win32gui.DeleteObject(savebitmap.GetHandle()) savedc.DeleteDC() mfcdc.DeleteDC() win32gui.ReleaseDC(self.hwnd, hwnddc) else: im = ImageGrab.grab() return im def get_game_bbox(self): logging.debug("Searching for game bounding box within client area.") screenshot = self.capture_screenshot() if self.mode == Mode.Window: left, top, right, bottom = win32gui.GetClientRect(self.hwnd) else: clientleft, clienttop, clientright, clientbottom = win32gui.GetClientRect(self.hwnd) left, top = win32gui.ClientToScreen(self.hwnd, (clientleft, clienttop)) right, bottom = win32gui.ClientToScreen(self.hwnd, (clientright, clientbottom)) logging.debug("Client rect: {},{},{},{}".format(left, top, right, bottom)) # Let's find the left edge blackcount = 0 y = int((bottom - top) / 2) + top + 100 left_found = False for x in range(left, left + 400): p = screenshot.getpixel((x, y)) if p[0] == 0 and p[1] == 0 and p[2] == 0: blackcount += 1 else: if blackcount > 10: left = x left_found = True break else: blackcount = 0 if not left_found: logging.error("Failed to find left edge.") raise Exception("Failed to find left edge.") # Let's find the top edge for y in range(top + 300, top - 1, -1): p = screenshot.getpixel((left - 1, y)) if p[0] != 0 or p[1] != 0 or p[2] != 0: top = y + 1 break if top < 0: logging.debug("Pixels were black to 0, assuming full screen.") top = 0 # Let's find the bottom edge for y in range(bottom - 20, bottom, +1): p = screenshot.getpixel((left - 1, y)) if p[0] != 0 or p[1] != 0 or p[2] != 0: # Let's assume if there's a border on the bottom, there's one on the right too. right -= bottom - y bottom = y break # Game window can only be 1500 pixels wide at most, cap the right side based on this. if right - left > 1500: right = left + 1500 # Game window can only be 900 pixels high. if bottom - top > 900: offset = int((bottom - top - 900) / 2) top += offset bottom = top + 900 logging.debug("Game position: {},{},{},{}".format(left, top, right, bottom)) self.gamepos = Rect(left, top, right, bottom) def game_to_client(self, x, y, xorient=Orient.Left, yorient=Orient.Top): if xorient == Orient.Center: x += int((self.gamepos.right - self.gamepos.left) / 2) + self.gamepos.left elif xorient == Orient.Right: x = self.gamepos.right - abs(x) elif xorient == Orient.Left: x += self.gamepos.left else: raise Exception("Invalid xorient.") if yorient == Orient.Center: y += int((self.gamepos.bottom - self.gamepos.top) / 2) + self.gamepos.top elif yorient == Orient.Bottom: y = self.gamepos.bottom - abs(y) elif yorient == Orient.Top: y += self.gamepos.top else: raise Exception("Invalid yorient.") return x, y def client_to_game(self, x, y, xorient=Orient.Left, yorient=Orient.Top): if xorient == Orient.Center: x -= int((self.gamepos.right - self.gamepos.left) / 2) + self.gamepos.left elif xorient == Orient.Right: x = abs(x - self.gamepos.right) elif xorient == Orient.Left: x -= self.gamepos.left else: raise Exception("Invalid xorient.") if yorient == Orient.Center: y -= int((self.gamepos.bottom - self.gamepos.top) / 2) + self.gamepos.top elif yorient == Orient.Bottom: y = abs(y - self.gamepos.bottom) elif yorient == Orient.Top: y -= self.gamepos.top else: raise Exception("Invalid yorient.") return x, y def click(self, x, y, xorient=Orient.Left, yorient=Orient.Top): x, y = self.game_to_client(x, y, xorient, yorient) logging.debug('Clicking {},{}'.format(x, y)) if self.mode == Mode.Window: position = makelong(x, y) win32gui.PostMessage(self.hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, position) time.sleep(0.01) win32gui.PostMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, position) else: oldx, oldy = win32api.GetCursorPos() win32api.SetCursorPos((x, y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) win32api.SetCursorPos((oldx, oldy)) def mouse_move(self, x, y, xorient=Orient.Left, yorient=Orient.Top): x, y = self.game_to_client(x, y, xorient, yorient) logging.debug('Moving mouse to {},{}'.format(x, y)) if self.mode == Mode.Window: position = makelong(x, y) win32gui.PostMessage(self.hwnd, win32con.WM_MOUSEMOVE, 0, position) else: win32api.SetCursorPos((x, y)) def mouse_get(self, xorient=Orient.Left, yorient=Orient.Top): x, y = win32gui.GetCursorPos() x, y = self.client_to_game(x, y, xorient, yorient) logging.debug('Mouse at game pos {}({}),{}({})'.format(x, xorient, y, yorient)) return x, y arrow_cursor = win32api.LoadCursor(0, win32con.IDC_ARROW) hand_cursor = win32api.LoadCursor(0, win32con.IDC_HAND) def check_cursor(self, x, y, cursor, xorient=Orient.Left, yorient=Orient.Top): if self.mode != Mode.Desktop: raise Exception("check_cursor can not be used in window mode, only desktop mode.") x, y = self.game_to_client(x, y, xorient, yorient) logging.debug('Checking if mouse cursor is hand at {},{}'.format(x, y)) # Jitter the mouse. self.mouse_move(x + 1, y + 1) time.sleep(0.010) self.mouse_move(x, y) time.sleep(0.010) flags, current_cursor, position = win32gui.GetCursorInfo() return current_cursor == cursor def image_find(self, image, x, y, xorient=Orient.Left, yorient=Orient.Top, screenshot=None, radius=2, threshold=None, great_threshold=None): """ Finds an image in the game and returns the client coordinates and offset. """ searchpos = self.game_to_client(x, y, xorient, yorient) if screenshot is None: screenshot = self.capture_screenshot() pos = image_search(screenshot, image, *searchpos, radius=radius, threshold=threshold, great_threshold=great_threshold) if pos[0] != -1: offsetx = searchpos[0] - pos[0] offsety = searchpos[1] - pos[1] pos = self.client_to_game(*pos) else: offsetx = 0 offsety = 0 return FoundPosition(pos[0], pos[1], offsetx, offsety) def find_back_button(self): if not "Back" in self.resources: self.resources['Back'] = Image.open(script_dir + '/misc/Back.png') # Arena back_pos = self.image_find(self.resources['Back'], 73, 65, Orient.Right, Orient.Bottom) # Domination if back_pos.x == -1: back_pos = self.image_find(self.resources['Back'], 135, 62, Orient.Center, Orient.Bottom) return back_pos def goto_homepage(self): back_found = True while back_found: back_found = False back_pos = self.find_back_button() if back_pos.x != -1: self.click(back_pos.x + 25, back_pos.y + 25) back_found = True time.sleep(2.000)
def __init__(self): self.alive = True # Icons based on game state icon_normal = path.realpath("notifyon.ico") icon_gray = path.realpath("notifyoff.ico") # Menu text color based on game state menu_gray = win32con.MF_STRING | win32con.MF_GRAYED menu_normal = win32con.MF_STRING self.menu_mindustry_flags = { GameState.NOT_FOUND: menu_gray, GameState.SCREENSHOT_FAIL: menu_normal, GameState.MINIMIZED: menu_normal, GameState.BOSS_WAVE: menu_normal, GameState.OTHER: menu_normal, } self.game_state = GameState.OTHER self.icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE self.nid_flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP # Register the window class message_map = { win32con.WM_DESTROY: self.on_destroy, win32con.WM_COMMAND: self.on_command, win32con.WM_USER + 20: self.on_taskbar_notify, } self.wc = win32gui.WNDCLASS() hinst = self.wc.hInstance = win32api.GetModuleHandle(None) self.wc.lpszClassName = "MindustryNotifierTaskbar" self.wc.lpfnWndProc = message_map self.wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW self.wc.hCursor = win32api.LoadCursor(0, win32con.IDC_ARROW) self.wc.hbrBackground = win32con.COLOR_WINDOW try: class_atom = win32gui.RegisterClass(self.wc) except win32gui.error as err: if err.winerror != winerror.ERROR_CLASS_ALREADY_EXISTS: raise # Create the window style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(class_atom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) # Create icons try: self.hicon_normal = win32gui.LoadImage(hinst, icon_normal, win32con.IMAGE_ICON, 0, 0, self.icon_flags) except Exception as err: self.hicon_normal = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) try: self.hicon_gray = win32gui.LoadImage(hinst, icon_gray, win32con.IMAGE_ICON, 0, 0, self.icon_flags) except Exception as err: self.hicon_gray = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) self.hicons = { GameState.NOT_FOUND: self.hicon_gray, GameState.SCREENSHOT_FAIL: self.hicon_gray, GameState.MINIMIZED: self.hicon_gray, GameState.BOSS_WAVE: self.hicon_normal, GameState.OTHER: self.hicon_normal, } nid = (self.hwnd, 0, self.nid_flags, win32con.WM_USER + 20, self.hicons[self.game_state], "Mindustry Notifier") try: win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) except win32gui.error: print( "Failed to create taskbar icon. Possibly explorer has crashed or has not yet started." )