def TestDeviceNotifications(dir_names): wc = win32gui.WNDCLASS() wc.lpszClassName = 'test_devicenotify' wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpfnWndProc = {win32con.WM_DEVICECHANGE: OnDeviceChange} class_atom = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow( wc.lpszClassName, 'Testing some devices', # no need for it to be visible. win32con.WS_CAPTION, 100, 100, 900, 900, 0, 0, 0, None) hdevs = [] # Watch for all USB device notifications filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE( GUID_DEVINTERFACE_USB_DEVICE) hdev = win32gui.RegisterDeviceNotification( hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE) hdevs.append(hdev) # and create handles for all specified directories for d in dir_names: hdir = win32file.CreateFile( d, winnt.FILE_LIST_DIRECTORY, winnt.FILE_SHARE_READ | winnt.FILE_SHARE_WRITE | winnt.FILE_SHARE_DELETE, None, # security attributes win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | # required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME. win32con.FILE_FLAG_OVERLAPPED, None) filter = win32gui_struct.PackDEV_BROADCAST_HANDLE(hdir) hdev = win32gui.RegisterDeviceNotification( hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE) hdevs.append(hdev) # now start a message pump and wait for messages to be delivered. print("Watching", len(hdevs), "handles - press Ctrl+C to terminate, or") print("add and remove some USB devices...") if not dir_names: print( "(Note you can also pass paths to watch on the command-line - eg,") print( "pass the root of an inserted USB stick to see events specific to") print("that volume)") while 1: win32gui.PumpWaitingMessages() time.sleep(0.01) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(wc.lpszClassName, None)
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
class SysTrayIcon(object): MENU_ITEM_ID_ABOUT = 1023 MENU_ITEM_ID_EXIT = 1024 free_menu_id = 1025 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 # 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 _SetupList(self): child_style = (win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER | win32con.WS_HSCROLL | win32con.WS_VSCROLL) child_style |= (commctrl.LVS_SINGLESEL | commctrl.LVS_SHOWSELALWAYS | commctrl.LVS_REPORT) self.hwndList = win32gui.CreateWindow( "SysListView32", None, child_style, 0, 0, 100, 100, self.hwnd, IDC_LISTBOX, self.hinst, None, ) child_ex_style = win32gui.SendMessage( self.hwndList, commctrl.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0) child_ex_style |= commctrl.LVS_EX_FULLROWSELECT win32gui.SendMessage(self.hwndList, commctrl.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, child_ex_style) # Add an image list - use the builtin shell folder icon - this # demonstrates the problem with alpha-blending of icons on XP if # winxpgui is not used in place of win32gui. il = win32gui.ImageList_Create( win32api.GetSystemMetrics(win32con.SM_CXSMICON), win32api.GetSystemMetrics(win32con.SM_CYSMICON), commctrl.ILC_COLOR32 | commctrl.ILC_MASK, 1, # initial size 0, ) # cGrow shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll") large, small = win32gui.ExtractIconEx(shell_dll, 4, 1) win32gui.ImageList_ReplaceIcon(il, -1, small[0]) win32gui.DestroyIcon(small[0]) win32gui.DestroyIcon(large[0]) win32gui.SendMessage(self.hwndList, commctrl.LVM_SETIMAGELIST, commctrl.LVSIL_SMALL, il) # Setup the list control columns. lvc = LVCOLUMN(mask=commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | commctrl.LVCF_SUBITEM) lvc.fmt = commctrl.LVCFMT_LEFT lvc.iSubItem = 1 lvc.text = "Title" lvc.cx = 200 win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0, lvc.toparam()) lvc.iSubItem = 0 lvc.text = "Order" lvc.cx = 50 win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0, lvc.toparam()) win32gui.UpdateWindow(self.hwnd)
def create_window(self): def editwndproc(hwnd, msg, wParam, lParam): # print("EW: %08x %08x %08x"%(msg, wParam, lParam)) if msg == win32con.WM_CHAR: if wParam == win32con.VK_RETURN: if self.exec_command(win32gui.GetWindowText( self.hwnd_edit)): return 0 if wParam == win32con.VK_ESCAPE: win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE) return 0 if msg == win32con.WM_KEYDOWN: if wParam == win32con.VK_UP: self.next_candidate(-1) return 0 if wParam == win32con.VK_DOWN: self.next_candidate(1) return 0 return win32gui.CallWindowProc(self.old_editwndproc, hwnd, msg, wParam, lParam) def wndproc(hwnd, msg, wParam, lParam): # FIXME: not print()ing in wndproc mysteriously cause "OSError: exception: access violation" print("MW: %08x %08x %08x" % (msg, wParam, lParam)) if msg == win32con.WM_COMMAND and win32api.HIWORD( wParam) == win32con.EN_CHANGE: text = win32gui.GetWindowText(self.hwnd_edit) if len(text) == 0: return 0 proposals = self.cmds.proposals(text) if not proposals: return 0 win32gui.SetWindowText(self.hwnd_edit, proposals[0]) win32api.SendMessage(self.hwnd_edit, win32con.EM_SETSEL, len(text), -1) if msg == win32con.WM_SETFOCUS: win32gui.SetFocus(self.hwnd_edit) windll.user32.DefWindowProcW.argtypes = (ctypes.wintypes.HWND, ctypes.wintypes.UINT, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM) return windll.user32.DefWindowProcW(hwnd, msg, wParam, lParam) # message_map = { # win32con.WM_DESTROY: self.OnDestroy, # } wc = win32gui.WNDCLASS() wc.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW wc.lpfnWndProc = wndproc wc.cbWndExtra = 0 wc.hCursor = 0 wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.hIcon = 0 wc.lpszClassName = "windhockey" wc.cbWndExtra = 0 win32gui.RegisterClass(wc) style = win32con.WS_OVERLAPPEDWINDOW self.hwnd = win32gui.CreateWindowEx( win32con.WS_EX_WINDOWEDGE, "windhockey", "windhockey", win32con.WS_CAPTION | win32con.WS_VISIBLE, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 256, 96, 0, 0, win32api.GetModuleHandle(None), None) self.hwnd_edit = win32gui.CreateWindow( "EDIT", "", win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.ES_NOHIDESEL, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 256, 96, self.hwnd, 0, win32api.GetModuleHandle(None), None) # seems pywin32 lacks SetWindowSubclass() self.old_editwndproc = win32gui.SetWindowLong(self.hwnd_edit, win32con.GWL_WNDPROC, editwndproc) # print(hex(self.old_editwndproc)) #font = win32ui.CreateFont({'name':'Courier New', 'height':96}) #win32gui.SendMessage(self.hwnd_edit, win32con.WM_SETFONT, font.GetSafeHandle(), True) win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)
def createWindow(title, className, width, height, xPosition=None, yPosition=None, icon=None, windowHandle=None): if not windowHandle: windowHandle = {win32con.WM_CLOSE: WM_CLOSE} windowClass = win32gui.WNDCLASS() windowClass.hInstance = win32api.GetModuleHandle(None) windowClass.lpszClassName = className windowClass.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW windowClass.hbrBackground = win32con.COLOR_WINDOW windowClass.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) windowClass.lpfnWndProc = windowHandle global g_registeredClasses if not className in g_registeredClasses: g_registeredClasses[className] = True win32gui.RegisterClass(windowClass) debug('win32gui..RegisterClass(%s)' % className) if xPosition is None or yPosition is None: debug('Centering window on screen.') screenX = win32api.GetSystemMetrics(win32con.SM_CXSCREEN) screenY = win32api.GetSystemMetrics(win32con.SM_CYSCREEN) xPosition = int(math.floor((screenX - width) / 2)) yPosition = int(math.floor((screenY - height) / 2)) if xPosition < 0: xPosition = 0 if yPosition < 0: yPosition = 0 windowId = win32gui.CreateWindow( className, title, win32con.WS_OVERLAPPEDWINDOW | win32con.WS_CLIPCHILDREN | win32con.WS_VISIBLE, xPosition, yPosition, width, height, 0, 0, windowClass.hInstance, None) g_windows[windowId] = className debug("windowId = %s" % windowId) if icon: icon = getApplicationPath(icon) bigIcon = win32gui.LoadImage( 0, icon, win32con.IMAGE_ICON, win32api.GetSystemMetrics(win32con.SM_CXICON), win32api.GetSystemMetrics(win32con.SM_CYICON), win32con.LR_LOADFROMFILE) smallIcon = win32gui.LoadImage( 0, icon, win32con.IMAGE_ICON, win32api.GetSystemMetrics(win32con.SM_CXSMICON), win32api.GetSystemMetrics(win32con.SM_CYSMICON), win32con.LR_LOADFROMFILE) win32api.SendMessage(windowId, win32con.WM_SETICON, win32con.ICON_BIG, bigIcon) win32api.SendMessage(windowId, win32con.WM_SETICON, win32con.ICON_SMALL, smallIcon) return windowId
class FileSystemView: _public_methods_ = shellcon.IShellView_Methods _com_interfaces_ = [pythoncom.IID_IOleWindow, shell.IID_IShellView, ] def __init__(self, folder, hwnd): self.hwnd_parent = hwnd # provided by explorer. self.hwnd = None # intermediate window for catching command notifications. self.hwnd_child = None # our ListView self.activate_state = None self.hmenu = None self.browser = None self.folder = folder self.children = None # IOleWindow def GetWindow(self): return self.hwnd def ContextSensitiveHelp(self, enter_mode): raise COMException(hresult=winerror.E_NOTIMPL) # IShellView def CreateViewWindow(self, prev, settings, browser, rect): print "FileSystemView.CreateViewWindow", prev, settings, browser, rect self.cur_foldersettings = settings self.browser = browser self._CreateMainWindow(prev, settings, browser, rect) self._CreateChildWindow(prev) def _CreateMainWindow(self, prev, settings, browser, rect): # Creates a parent window that hosts the view window. This window # gets the control notifications etc sent from the child. style = win32con.WS_CHILD | win32con.WS_VISIBLE # wclass_name = "ShellViewDemo_DefView" # Register the Window class. wc = win32gui.WNDCLASS() wc.hInstance = win32gui.dllhandle wc.lpszClassName = wclass_name wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW try: win32gui.RegisterClass(wc) except win32gui.error, details: # Should only happen when this module is reloaded if details[0] != winerror.ERROR_CLASS_ALREADY_EXISTS: raise message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_NOTIFY: self.OnNotify, win32con.WM_CONTEXTMENU: self.OnContextMenu, win32con.WM_SIZE: self.OnSize, } self.hwnd = win32gui.CreateWindow( wclass_name, "", style, \ rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1], self.hwnd_parent, 0, win32gui.dllhandle, None) win32gui.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, message_map) print "View 's hwnd is", self.hwnd return self.hwnd
def __init__(self, agent_status, salt_status, check_status, mesh_status): self.agent_status = agent_status self.salt_status = salt_status self.check_status = check_status self.mesh_status = mesh_status self.icon = os.path.join(os.getcwd(), "onit.ico") win32gui.InitCommonControls() self.hinst = win32api.GetModuleHandle(None) className = "AgentStatus" message_map = { win32con.WM_DESTROY: self.OnDestroy, } wc = win32gui.WNDCLASS() wc.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW try: wc.hIcon = win32gui.LoadImage( self.hinst, self.icon, win32con.IMAGE_ICON, 0, 0, win32con.LR_LOADFROMFILE, ) except Exception: pass wc.lpfnWndProc = message_map wc.lpszClassName = className win32gui.RegisterClass(wc) style = win32con.WS_OVERLAPPEDWINDOW self.hwnd = win32gui.CreateWindow( className, "Tactical RMM", style, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 400, 300, 0, 0, self.hinst, None, ) win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW) hDC, paintStruct = win32gui.BeginPaint(self.hwnd) rect = win32gui.GetClientRect(self.hwnd) win32gui.DrawText( hDC, f"Agent: {self.agent_status}", -1, (0, 0, 384, 201), win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER, ) win32gui.DrawText( hDC, f"Check Runner: {self.check_status}", -1, (0, 0, 384, 241), win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER, ) win32gui.DrawText( hDC, f"Salt Minion: {self.salt_status}", -1, (0, 0, 384, 281), win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER, ) win32gui.DrawText( hDC, f"Mesh Agent: {self.mesh_status}", -1, (0, 0, 384, 321), win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER, ) win32gui.EndPaint(self.hwnd, paintStruct) win32gui.UpdateWindow(self.hwnd)
def BuildWindow(self, className): style = win32con.WS_OVERLAPPEDWINDOW self.hwnd = win32gui.CreateWindow(className, "ThisIsJustATest", style, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 100, 100, 0, 0, self.hinst, None)
dc, ps=win32gui.BeginPaint(hwnd) win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED) l,t,r,b=win32gui.GetClientRect(hwnd) br=win32gui.CreateSolidBrush(win32api.RGB(0,0,255)) win32gui.SelectObject(dc, br) win32gui.FillRect(dc,(200+dx,200+dx,100+dx,100+dx),br) dx=(dx+10)%100 win32gui.EndPaint(hwnd, ps) return 0 wc = win32gui.WNDCLASS() wc.lpszClassName = 'win32' wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW+1 wndproc={win32con.WM_PAINT:OnPaint} wc.lpfnWndProc=wndproc wc.hCursor = win32gui.LoadCursor (None, win32con.IDC_ARROW) class_atom=win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow(class_atom,'hello', win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE, 350,120,640,480, 0, 0, 0, None) for x in range(30): win32gui.InvalidateRect(hwnd,None,True) win32gui.PumpWaitingMessages() time.sleep(0.3) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(class_atom,None)
def createWindowClassic(self, classAtom): hwnd = win32gui.CreateWindow(classAtom, "QQ2013 Xmas", self.WINDOW_STYLE, self.cfg.windowX, self.cfg.windowY, self.cfg.windowWidth, self.cfg.windowHeight, 0, 0, 0, None) return hwnd
def wndProc(hwnd, msg, wParam, lParam): if msg == win32con.WM_CREATE: print('message: WM_CREATE') if msg == win32con.WM_SIZE: print('message: WM_SIZE') if msg == win32con.WM_PAINT: print('message: WM_PAINT') if msg == win32con.WM_CLOSE: print('message: WM_CLOSE') if msg == win32con.WM_DESTROY: print('message: WM_DESTROY') win32gui.PostQuitMessage(0) return win32gui.DefWindowProc(hwnd, msg, wParam, lParam) wndClsStruct = win32gui.WNDCLASS() wndClsStruct.hbrBackground = win32con.COLOR_BTNFACE + 1 wndClsStruct.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wndClsStruct.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) wndClsStruct.lpszClassName = "MySimpleWindow" wndClsStruct.lpfnWndProc = wndProc wndClassAtom = win32gui.RegisterClass(wndClsStruct) hwnd = win32gui.CreateWindow(wndClassAtom, 'MySimpleWindow', win32con.WS_OVERLAPPEDWINDOW, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, 0, None) win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL) win32gui.UpdateWindow(hwnd) win32gui.PumpMessages()
def CreateWindowX(self, WndClass, WinGuiClassAtom, szTitle, Transparent=True): hight, width = self.GetDesktopHW() if self.Ex: if Transparent: # hWindow = self.CreateWindowEx( # win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED, # WndClass.lpszClassName, # szTitle, # win32con.WS_POPUP, # 0, # 0, # width, # hight, # 0, # 0, # WndClass.hInstance, # None) hWindow = self.CreateWindowEx( win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED, WndClass.lpszClassName, szTitle, win32con.WS_POPUP, 0, 0, width, hight, 0, 0, WndClass.hInstance, None) else: hWindow = self.CreateWindowEx( win32con.WS_EX_TOPMOST, WndClass.lpszClassName, szTitle, win32con.WS_OVERLAPPEDWINDOW, # win32con.WS_OVERLAPPEDWINDOW | win32con.WS_CAPTION 0, 0, width, hight, 0, 0, WndClass.hInstance, None) else: if Transparent: hWindow = win32gui.CreateWindow( WinGuiClassAtom, #it seems message dispatching only works with the atom, not the class name szTitle, win32con.WS_OVERLAPPEDWINDOW, 0, 0, width, hight, 0, 0, WndClass.hInstance, None) else: hWindow = win32gui.CreateWindow( WinGuiClassAtom, #it seems message dispatching only works with the atom, not the class name szTitle, win32con.WS_OVERLAPPEDWINDOW, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, WndClass.hInstance, None) # hWindow = win32gui.CreateWindow( # WinGuiClassAtom, #it seems message dispatching only works with the atom, not the class name # szTitle, # win32con.WS_POPUP, # 0, # 0, # width, # hight, # 0, # 0, # WndClass.hInstance, # None) return hWindow
win32gui.PostQuitMessage(0) #Define message map for window wndproc = { win32con.WM_PAINT: OnPaint, win32con.WM_CLOSE: OnClose, win32con.WM_DESTROY: OnDestroy } def CreateWindow(title, message_map, (l, t, r, b)): """Create a window with defined title, message map, and rectangle""" wc = win32gui.WNDCLASS() wc.lpszClassName = 'test_win32gui_1' wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wc.lpfnWndProc = message_map class_atom = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow( wc.lpszClassName, title, win32con.WS_CAPTION | win32con.WS_VISIBLE | win32con.WS_SYSMENU, l, t, r, b, 0, 0, 0, None) while win32gui.PumpWaitingMessages() == 0: time.sleep(0.01) win32gui.UnregisterClass(wc.lpszClassName, None) #Display sample window CreateWindow('Pywin32 sample', wndproc, (100, 100, 500, 200))
def CreateComboBox(parent, pos, size, style=wc.CBS_DROPDOWNLIST): parent_hwnd = parent.GetSafeHwnd() hwnd = gui.CreateWindow("COMBOBOX", "Blarg", wc.WS_CHILD | wc.CBS_DROPDOWNLIST, pos[0], pos[1], size[0], size[1], parent_hwnd, 0, 0, None) return ui.CreateWindowFromHandle(hwnd)
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): """ Perform Windows Notification """ if not self._enabled: self.logger.warning( "Windows Notifications are not supported by this system.") return False # Always call throttle before any remote server i/o is made self.throttle() try: # Register destruction callback message_map = { win32con.WM_DESTROY: self._on_destroy, } # Register the window class. self.wc = win32gui.WNDCLASS() self.hinst = self.wc.hInstance = win32api.GetModuleHandle(None) self.wc.lpszClassName = str("PythonTaskbar") self.wc.lpfnWndProc = message_map self.classAtom = win32gui.RegisterClass(self.wc) # Styling and window type style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(self.classAtom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, self.hinst, None) win32gui.UpdateWindow(self.hwnd) # image path (if configured to acquire) icon_path = None if not self.include_image \ else self.image_path(notify_type, extension='.ico') if icon_path: icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE try: hicon = win32gui.LoadImage(self.hinst, icon_path, win32con.IMAGE_ICON, 0, 0, icon_flags) except Exception as e: self.logger.warning( "Could not load windows notification icon ({}): {}". format(icon_path, e)) # disable icon hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) else: # disable icon hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) # Taskbar icon flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, "Tooltip") win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) win32gui.Shell_NotifyIcon( win32gui.NIM_MODIFY, (self.hwnd, 0, win32gui.NIF_INFO, win32con.WM_USER + 20, hicon, "Balloon Tooltip", body, 200, title)) # take a rest then destroy sleep(self.duration) win32gui.DestroyWindow(self.hwnd) win32gui.UnregisterClass(self.wc.lpszClassName, None) self.logger.info('Sent Windows notification.') except Exception: self.logger.warning('Failed to send Windows notification.') self.logger.exception('Windows Exception') return False return True
def notify(self, title, body, notify_type, **kwargs): """ Perform Windows Notification """ if not self._enabled: self.logger.warning( "Windows Notifications are not supported by this system.") return False # Limit results to just the first 2 line otherwise # there is just to much content to display body = re.split('[\r\n]+', body) body[0] = body[0].strip('#').strip() body = '\r\n'.join(body[0:2]) try: # Register destruction callback message_map = { win32con.WM_DESTROY: self._on_destroy, } # Register the window class. self.wc = win32gui.WNDCLASS() self.hinst = self.wc.hInstance = win32api.GetModuleHandle(None) self.wc.lpszClassName = str("PythonTaskbar") self.wc.lpfnWndProc = message_map self.classAtom = win32gui.RegisterClass(self.wc) # Styling and window type style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(self.classAtom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, self.hinst, None) win32gui.UpdateWindow(self.hwnd) # image path icon_path = self.image_path(notify_type, extension='.ico') icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE try: hicon = win32gui.LoadImage(self.hinst, icon_path, win32con.IMAGE_ICON, 0, 0, icon_flags) except Exception as e: self.logger.warning( "Could not load windows notification icon ({}): {}".format( icon_path, e)) # disable icon hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) # Taskbar icon flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, "Tooltip") win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) win32gui.Shell_NotifyIcon( win32gui.NIM_MODIFY, (self.hwnd, 0, win32gui.NIF_INFO, win32con.WM_USER + 20, hicon, "Balloon Tooltip", body, 200, title)) # take a rest then destroy sleep(self.duration) win32gui.DestroyWindow(self.hwnd) win32gui.UnregisterClass(self.wc.lpszClassName, None) self.logger.info('Sent Windows notification.') except Exception as e: self.logger.warning('Failed to send Windows notification.') self.logger.exception('Windows Exception') return False return True
def CreateWindow(title, className, width, height, xpos=None, ypos=None, icon=None, windowProc=None): """ for key in g_windows: if g_windows[key] == className: raise Exception("There was already created a window with that className: %s." "Each created window must have an unique className." % className) """ if not windowProc: windowProc = {win32con.WM_CLOSE: WM_CLOSE} bigIcon = "" smallIcon = "" if icon: icon = GetRealPath(icon) # Load small and big icon. # WNDCLASSEX (along with hIconSm) is not supported by pywin32, # we need to use WM_SETICON message after window creation. # http://stackoverflow.com/questions/2234988/how-to-set-hicon-on-a-window-ico-with-multiple-sizes # http://blog.barthe.ph/2009/07/17/wmseticon/ bigX = win32api.GetSystemMetrics(win32con.SM_CXICON) bigY = win32api.GetSystemMetrics(win32con.SM_CYICON) bigIcon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, bigX, bigY, win32con.LR_LOADFROMFILE) smallX = win32api.GetSystemMetrics(win32con.SM_CXSMICON) smallY = win32api.GetSystemMetrics(win32con.SM_CYSMICON) smallIcon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, smallX, smallY, win32con.LR_LOADFROMFILE) wndclass = win32gui.WNDCLASS() wndclass.hInstance = win32api.GetModuleHandle(None) wndclass.lpszClassName = className wndclass.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW # win32con.CS_GLOBALCLASS wndclass.hbrBackground = win32con.COLOR_WINDOW wndclass.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wndclass.lpfnWndProc = windowProc #noinspection PyUnusedLocal global g_registeredClasses if not className in g_registeredClasses: g_registeredClasses[className] = True atomclass = win32gui.RegisterClass(wndclass) Debug("win32gui.RegisterClass(%s)" % className) if xpos is None or ypos is None: # Center window on the screen. Debug("Centering window on the screen.") screenx = win32api.GetSystemMetrics(win32con.SM_CXSCREEN) screeny = win32api.GetSystemMetrics(win32con.SM_CYSCREEN) xpos = int(math.floor((screenx - width) / 2)) ypos = int(math.floor((screeny - height) / 2)) if xpos < 0: xpos = 0 if ypos < 0: ypos = 0 windowID = win32gui.CreateWindow( className, title, win32con.WS_OVERLAPPEDWINDOW | win32con.WS_CLIPCHILDREN | win32con.WS_VISIBLE, xpos, ypos, width, height, # xpos, ypos, width, height 0, 0, wndclass.hInstance, None) g_windows[windowID] = className if icon: if bigIcon: win32api.SendMessage(windowID, win32con.WM_SETICON, win32con.ICON_BIG, bigIcon) if smallIcon: win32api.SendMessage(windowID, win32con.WM_SETICON, win32con.ICON_SMALL, smallIcon) Debug("windowID = %s" % windowID) return windowID
def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_SIZE: self.OnSize, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "test_explorer_browser" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE self.hwnd = win32gui.CreateWindow( classAtom, "Python IExplorerBrowser demo", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None, ) eb = pythoncom.CoCreateInstance( shellcon.CLSID_ExplorerBrowser, None, pythoncom.CLSCTX_ALL, shell.IID_IExplorerBrowser, ) # as per MSDN docs, hook up events early self.event_cookie = eb.Advise(wrap(EventHandler())) eb.SetOptions(shellcon.EBO_SHOWFRAMES) rect = win32gui.GetClientRect(self.hwnd) # Set the flags such that the folders autoarrange and non web view is presented flags = (shellcon.FVM_LIST, shellcon.FWF_AUTOARRANGE | shellcon.FWF_NOWEBVIEW) eb.Initialize(self.hwnd, rect, (0, shellcon.FVM_DETAILS)) if len(sys.argv) == 2: # If an arg was specified, ask the desktop parse it. # You can pass anything explorer accepts as its '/e' argument - # eg, "::{guid}\::{guid}" etc. # "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" is "My Computer" pidl = shell.SHGetDesktopFolder().ParseDisplayName(0, None, sys.argv[1])[1] else: # And start browsing at the root of the namespace. pidl = [] eb.BrowseToIDList(pidl, shellcon.SBSP_ABSOLUTE) # and for some reason the "Folder" view in the navigator pane doesn't # magically synchronize itself - so let's do that ourself. # Get the tree control. sp = eb.QueryInterface(pythoncom.IID_IServiceProvider) try: tree = sp.QueryService( shell.IID_INameSpaceTreeControl, shell.IID_INameSpaceTreeControl ) except pythoncom.com_error as exc: # this should really only fail if no "nav" frame exists... print( "Strange - failed to get the tree control even though " "we asked for a EBO_SHOWFRAMES" ) print(exc) else: # get the IShellItem for the selection. si = shell.SHCreateItemFromIDList(pidl, shell.IID_IShellItem) # set it to selected. tree.SetItemState(si, shellcon.NSTCIS_SELECTED, shellcon.NSTCIS_SELECTED) # eb.FillFromObject(None, shellcon.EBF_NODROPTARGET); # eb.SetEmptyText("No known folders yet..."); self.eb = eb
def WndProc(hwnd, msg, wParam, lParam): if msg == WM_PAINT: hdc, ps = win32gui.BeginPaint(hwnd) rect = win32gui.GetClientRect(hwnd) win32gui.DrawText(hdc, 'GUI Python', len('GUI Python'), rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER) win32gui.EndPaint(hwnd, ps) if msg == WM_DESTROY: win32gui.PostQuitMessage(0) return win32gui.DefWindowProc(hwnd, msg, wParam, lParam) wc = win32gui.WNDCLASS() wc.hbrBackground = COLOR_BTNFACE + 1 wc.hCursor = win32gui.LoadCursor(0, IDC_ARROW) wc.hIcon = win32gui.LoadIcon(0, IDI_APPLICATION) wc.lpszClassName = 'Python on Windows' wc.lpfnWndProc = WndProc reg = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow(reg, 'Python', WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, 0, None) win32gui.ShowWindow(hwnd, SW_SHOWNORMAL) win32gui.UpdateWindow(hwnd) win32gui.PumpMessages()
if os.path.isdir(filename): _files = scan_files(filename) else: _files = [filename] if len(_files) > 0: for _f in _files: fileHandler(_f) win32api.DragFinish(hDropInfo) return win32gui.DefWindowProc(hwnd, msg, wParam, lParam) wc = win32gui.WNDCLASS() wc.hbrBackground = COLOR_BTNFACE + 1 wc.hCursor = win32gui.LoadCursor(0, IDI_APPLICATION) wc.lpszClassName = "RDMinfoSystem no Windows" wc.lpfnWndProc = WndProc reg = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow(reg, u'研发管理信息系统:外部数据采集器', WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, 0, None) win32gui.SetWindowPos( hwnd, win32con.HWND_TOPMOST, 0, 0, 320, 120, win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW) win32gui.ShowWindow(hwnd, SW_SHOWNORMAL) win32gui.UpdateWindow(hwnd) win32gui.PumpMessages()
def __call__(self, title="", msg="", payload=None, iconOpt=ICON_EG, sound=True): """ Show a tip balloon in the Windows Event Center. title: Bold text to show in the title of the tip. msg: Detail text to show in the tip. payload: Python data to include with events triggered from this tip. iconOpt: an int or a string: 0 = No icon 1 = Info icon 2 = Warning icon 3 = Error icon 4 = EventGhost icon string = *full path* to an icon file, a semicolon, and the icon number (eg: "C:\\Windows\\system32\\shell32.dll;13") sound: Whether to play the notification sound. """ if iconOpt is None: iconOpt = self.ICON_EG title = eg.ParseString(title or "EventGhost") msg = eg.ParseString(msg or "This is a notification from EventGhost.") if payload and isinstance(payload, basestring): payload = eg.ParseString(payload) # https://stackoverflow.com/a/17262942/6692652 # Create the window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU hwnd = win32gui.CreateWindow(self.plugin.classAtom, "TaskBar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, self.plugin.hinst, None) win32gui.UpdateWindow(hwnd) self.plugin.setPayload(hwnd, payload) # Icons management # Default to no icon if something goes weird hicon = None dwInfoFlags = 0x00 try: if iconOpt == self.ICON_INFO: dwInfoFlags = NIIF_INFO | NIIF_LARGE_ICON elif iconOpt == self.ICON_WARNING: dwInfoFlags = NIIF_WARNING | NIIF_LARGE_ICON elif iconOpt == self.ICON_ERROR: dwInfoFlags = NIIF_ERROR | NIIF_LARGE_ICON elif iconOpt == self.ICON_EG: # Get the first icon from the EventGhost executable hicon = win32gui.CreateIconFromResource( win32api.LoadResource(None, win32con.RT_ICON, 1), True) dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON elif isinstance(iconOpt, basestring): filename, idx = iconOpt.split(";", 1) filename = expandvars(filename) dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON if filename[-4:].upper() == ".ICO": hicon = win32gui.LoadImage( win32api.GetModuleHandle(None), filename, win32con.IMAGE_ICON, 0, 0, win32con.LR_LOADFROMFILE | win32con.LR_LOADREALSIZE, ) else: lib = win32api.LoadLibrary(filename) hicon = win32gui.LoadIcon(lib, int(idx) + 1) win32api.FreeLibrary(lib) except Exception as ex: eg.PrintError(str(ex)) hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) dwInfoFlags = 0x00 if not sound: dwInfoFlags |= NIIF_NOSOUND flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP nid = (hwnd, 0, flags, WM_TRAYICON, hicon, 'Tooltip') # Notify win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) win32gui.Shell_NotifyIcon( win32gui.NIM_MODIFY, (hwnd, 0, win32gui.NIF_INFO, WM_TRAYICON, hicon, 'Balloon Tooltip', msg, 200, title, dwInfoFlags)) if hicon is not None: win32gui.DestroyIcon(hicon)
class FileSystemView: _public_methods_ = shellcon.IShellView_Methods _com_interfaces_ = [pythoncom.IID_IOleWindow, shell.IID_IShellView, ] def __init__(self, folder, hwnd): self.hwnd_parent = hwnd # provided by explorer. self.hwnd = None # intermediate window for catching command notifications. self.hwnd_child = None # our ListView self.activate_state = None self.hmenu = None self.browser = None self.folder = folder self.children = None # IOleWindow def GetWindow(self): return self.hwnd def ContextSensitiveHelp(self, enter_mode): raise COMException(hresult=winerror.E_NOTIMPL) # IShellView def CreateViewWindow(self, prev, settings, browser, rect): print "FileSystemView.CreateViewWindow", prev, settings, browser, rect self.cur_foldersettings = settings self.browser = browser self._CreateMainWindow(prev, settings, browser, rect) self._CreateChildWindow(prev) # This isn't part of the sample, but the most convenient place to # test/demonstrate how you can get an IShellBrowser from a HWND # (but ONLY when you are in the same process as the IShellBrowser!) # Obviously it is not necessary here - we already have the browser! browser_ad = win32gui.SendMessage(self.hwnd_parent, win32con.WM_USER+7, 0, 0) browser_ob = pythoncom.ObjectFromAddress(browser_ad, shell.IID_IShellBrowser) assert browser==browser_ob # and make a call on the object to prove it doesn't die :) assert browser.QueryActiveShellView()==browser_ob.QueryActiveShellView() def _CreateMainWindow(self, prev, settings, browser, rect): # Creates a parent window that hosts the view window. This window # gets the control notifications etc sent from the child. style = win32con.WS_CHILD | win32con.WS_VISIBLE # wclass_name = "ShellViewDemo_DefView" # Register the Window class. wc = win32gui.WNDCLASS() wc.hInstance = win32gui.dllhandle wc.lpszClassName = wclass_name wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW try: win32gui.RegisterClass(wc) except win32gui.error, details: # Should only happen when this module is reloaded if details[0] != winerror.ERROR_CLASS_ALREADY_EXISTS: raise message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_NOTIFY: self.OnNotify, win32con.WM_CONTEXTMENU: self.OnContextMenu, win32con.WM_SIZE: self.OnSize, } self.hwnd = win32gui.CreateWindow( wclass_name, "", style, \ rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1], self.hwnd_parent, 0, win32gui.dllhandle, None) win32gui.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, message_map) print "View 's hwnd is", self.hwnd return self.hwnd
def __init__(self, instance_num, icon, tray_ctrl_Q, hover_text, menu_options, on_ports_change, on_quit=None, default_menu_index=None, window_class_name=None, realtime=None): self._ports_change_count = 0 self._ports_change_type = '' self._ipaddr_change_count = 0 self._instance_num = instance_num self.icon = icon self.tray_ctrl_Q = tray_ctrl_Q self.__menu_extra = {} self.__realtime = realtime if realtime else 0 self.__dev_change_delay_timer_len = 50 if self.__realtime else 300 self.hover_text = hover_text self._on_ports_change = on_ports_change self.on_quit = on_quit self._show_main_win_callback = None self._keyevent_callback = None menu_options = menu_options + (('Quit', None, False, self.QUIT), ) self._next_action_id = self.FIRST_ID self.menu_actions_by_id = dict() self.menu_options = self._add_ids_to_menu_options(list(menu_options)) del self._next_action_id self.default_menu_index = (default_menu_index or 0) self.window_class_name = window_class_name or "SysTrayIconPy" self.__extern_timer_callback = None self.__extern_timer_cnt = 0 message_map = { win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart, #win32con.WM_CREATE: self.onCreate, win32con.WM_TIMER: self.onTimer, win32con.WM_DESTROY: self.destroy, win32con.WM_COMMAND: self.command, #win32con.WM_KEYUP: self.keyup, #win32con.WM_KEYDOWN: self.keydown, win32con.WM_DEVICECHANGE: self.winDeviceEvent, win32con.WM_USER + self.WM_USER_NOTIFY: self.notify, win32con.WM_USER + self.WM_USER_IP_CHANGED: self.onWinIpChangedProc } # Register the Window class. window_class = win32gui.WNDCLASS() hinst = window_class.hInstance = win32gui.GetModuleHandle(None) window_class.lpszClassName = self.window_class_name window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) window_class.hbrBackground = win32con.COLOR_WINDOW window_class.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(window_class) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(classAtom, self.window_class_name, style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) self.setupNotification() #sss win32gui.UpdateWindow(self.hwnd) user32.SetTimer(self.hwnd, self.ID_TIMER_FIRST_ONCE, 100, win32con.NULL) self.notify_id = None self.refresh_icon()