uiautomation

raw JSON →
2.0.29 verified Mon Apr 27 auth: no python

Python library for Windows UI Automation, enabling control of desktop applications via Microsoft UI Automation API. Current version 2.0.29, active development with occasional releases.

pip install uiautomation
error ImportError: cannot import name 'Control' from 'uiautomation'
cause Old import pattern; Control is not directly exported, use WindowControl etc.
fix
Use 'from uiautomation import WindowControl' or 'auto.WindowControl'.
error AttributeError: module 'uiautomation' has no attribute 'WindowControl'
cause Outdated version (<1.0) or incorrect installation.
fix
Upgrade: pip install --upgrade uiautomation
error comtypes.COMError: (-2147221008, 'CoInitialize has not been called.', ...)
cause COM not initialized in current thread.
fix
Call 'auto.CoInitializeEx(0)' at start of script.
error uiautomation.controls.ControlNotFoundException: Cannot find control
cause Search criteria too strict or wrong searchDepth.
fix
Increase searchDepth or use Control(searchFromControl=desktop). Example: auto.GetRootControl()
breaking Python 3.12+ may break due to changes in ctypes and COM. Tested up to 3.11.
fix Use Python 3.11 or lower, or monitor GitHub issues for compatibility fixes.
gotcha Controls are found with 'searchDepth' or 'searchFromRoot=False'. Default searchDepth is 0 (immediate children) which often finds nothing.
fix Always specify searchDepth (e.g., 1 for top-level windows) or use Control(searchFromControl=root).
gotcha SendKeys may not work on elevated (admin) apps if script is not elevated.
fix Run script as administrator or use SetFocus before SendKeys.

Finds Notepad window, sends text, and closes it.

import uiautomation as auto

# Launch Notepad if not running
if not auto.WindowControl(searchDepth=1, Name='Untitled - Notepad').Exists(0,0):
    os.system('notepad')
    time.sleep(1)

window = auto.WindowControl(searchDepth=1, Name='Untitled - Notepad')
edit = window.EditControl()
edit.Click()
edit.SendKeys('Hello, UI Automation!')
print('Text sent.')
window.GetWindowPattern().Close()