python-3.xwinapictypespywin32win32gui

python3 ctype CreateWindowEx simple example


I have googled for some time but could not find simple example of python3 ctypes and Win32 API for creating and showing window. Please point me to good link or show code here.

Thanks in advance!


Solution

  • This is most easy to do with the win32gui module and its friends, win32api and win32con. There's no need to write your own ctypes wrappers to the Windows API. The simplest Petzold style app comes out something like this:

    import win32api, win32con, win32gui
    
    class MyWindow:
    
        def __init__(self):
            win32gui.InitCommonControls()
            self.hinst = win32api.GetModuleHandle(None)
            className = 'MyWndClass'
            message_map = {
                win32con.WM_DESTROY: self.OnDestroy,
            }
            wc = win32gui.WNDCLASS()
            wc.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW
            wc.lpfnWndProc = message_map
            wc.lpszClassName = className
            win32gui.RegisterClass(wc)
            style = win32con.WS_OVERLAPPEDWINDOW
            self.hwnd = win32gui.CreateWindow(
                className,
                'My win32api app',
                style,
                win32con.CW_USEDEFAULT,
                win32con.CW_USEDEFAULT,
                300,
                300,
                0,
                0,
                self.hinst,
                None
            )
            win32gui.UpdateWindow(self.hwnd)
            win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
    
        def OnDestroy(self, hwnd, message, wparam, lparam):
            win32gui.PostQuitMessage(0)
            return True
    
    w = MyWindow()
    win32gui.PumpMessages()