Win32gui Site

1. Overview win32gui is a Python module that wraps a significant portion of the Microsoft Windows User Interface (UI) API, also known as the Win32 GUI API. It is part of the pywin32 (formerly win32all ) package, a set of Python extensions providing access to many Windows-specific functions, COM, and the Windows registry.

# Ensure visible and focused win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) win32gui.SetForegroundWindow(hwnd) win32gui

def automate_notepad(): hwnd = win32gui.FindWindow(None, "Untitled - Notepad") if not hwnd: print("Notepad not found") return # Ensure visible and focused win32gui

# Get handle of Edit control edit = win32gui.FindWindowEx(hwnd, None, "Edit", None) if not edit: print("Edit control not found") return | | Threading | Sending messages across threads

hdc = win32gui.GetWindowDC(hwnd) mfc_dc = win32ui.CreateDCFromHandle(hdc) save_dc = mfc_dc.CreateCompatibleDC() bitmap = win32ui.CreateBitmap() bitmap.CreateCompatibleBitmap(mfc_dc, width, height) save_dc.SelectObject(bitmap) save_dc.BitBlt((0, 0), (width, height), mfc_dc, (0, 0), win32con.SRCCOPY)

bmpinfo = bitmap.GetInfo() bmpstr = bitmap.GetBitmapBits(True) img = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) img.save('window_screenshot.png') pip install pywin32 After installation, you may need to run:

python Scripts/pywin32_postinstall.py -install (though recent versions handle this automatically) | Issue | Description | |-------|-------------| | UAC / Admin rights | Cannot interact with elevated windows from a non-elevated process. | | Modern UI (UWP, WinUI, WebView2) | Standard win32gui messages may not work; need UI Automation (e.g., uiautomation module). | | No built-in OCR/recognition | You must know window/control class names or use relative coordinates. | | Threading | Sending messages across threads can deadlock if not careful. | | 64-bit vs 32-bit | Handles are 64-bit on 64-bit Python – ensure your pywin32 matches Python arch. | 7. Alternatives & Complementary Libraries | Library | When to use | |---------|--------------| | PyGetWindow | Simpler window management, but less powerful. | | PyAutoGUI | Screen coordinates, image recognition, keyboard/mouse simulation. | | uiautomation / pywinauto | Modern Windows apps (UWP, WinForms, WPF) – uses MS UI Automation. | | ctypes + user32.dll | Direct Win32 API calls without pywin32 . | | pynput | Cross-platform keyboard/mouse listeners. | 8. Example: Real-World Automation Task Goal: Find a Notepad window, write the current date/time, save the file.