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.
import win32gui import win32con import win32clipboard from datetime import datetime def set_clipboard_text(text): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text) win32clipboard.CloseClipboard() win32gui
def automate_notepad(): hwnd = win32gui.FindWindow(None, "Untitled - Notepad") if not hwnd: print("Notepad not found") return | | Threading | Sending messages across threads
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. write the current date/time
# Set text via clipboard (simpler for large text) text = f"Automated entry at datetime.now()" set_clipboard_text(text) win32gui.SendMessage(edit, win32con.WM_PASTE, 0, 0)