三、示例代码

下面示例均可直接复制。请先完成 安装,并打开对应窗口。

每个示例都尽量写成「从头到尾可运行」:含导入、找窗口、激活、操作、打印结果。
WIN_CLASS / WIN_TITLE_KEY 改成你的目标即可。


通用调试头(强烈建议每个脚本都这么写)

# -*- coding: utf-8 -*-
from winautox import WinAuto
import time

WIN_CLASS = 'Notepad'            # ← 改成目标窗口 ClassName
WIN_TITLE_KEY = '记事本'          # ← 标题包含即可,不必写全

def bind_auto(mode='uia'):
    hwnd = WinAuto.find_hwnd(WIN_CLASS, WIN_TITLE_KEY)
    if not hwnd:
        raise RuntimeError(
            f'未找到窗口 class={WIN_CLASS!r} 标题含 {WIN_TITLE_KEY!r}。'
            f'请先打开目标程序,或用 dump 核对 ClassName。'
        )
    auto = WinAuto(hwnd, mode=mode, delay=0.15)
    auto.activate()
    time.sleep(0.3)
    print(f'[bind] hwnd={hwnd} mode={mode}')
    return auto

auto = bind_auto()

后面示例默认假设你已经有 auto(或把 bind_auto() 贴进同一文件)。


示例 1:打印控件树(学会自动化的第一步)

用途:不知道按钮叫什么、输入框 aid 是什么时,先看树。

auto = bind_auto()

wins = auto.dump_windows_controls(max_windows=20, max_lines=800)
print('=== 顶层窗口列表 ===')
for w in wins:
    print('hwnd=', w.get('hwnd'), 'class=', w.get('class_name'), 'title=', w.get('title'))

print('=== 控件树(请在输出里搜索你要点的按钮文字)===')
WinAuto.print_windows_dump(wins)

你会看到什么:大量行,每行类似控件类型 + Name + AutomationId。
用编辑器 Ctrl+F 搜界面上的字,把找到的 name / aid 抄到后面的 click / find 里。


示例 2:等待控件出现再点

用途:按钮要过一会儿才出现(加载中、弹窗动画)。

auto = bind_auto()

btn = auto.wait_ctrl(
    ctrl_type='ButtonControl',
    name='确定',          # ← 改成真实按钮 Name
    timeout=5.0,         # 最多等 5 秒
)
if btn:
    print('出现了,点击')
    auto.click(btn, mode='uia')
else:
    print('超时仍未出现「确定」。请 dump 核对 Name,或加大 timeout。')

示例 3:输入并回车发送

用途:聊天框、搜索框、表单输入。

auto = bind_auto()

# 优先用 aid(更稳);没有 aid 再试 name / 只按类型
edit = auto.find(ctrl_type='EditControl', aid='chat_input', depth=15)
if edit is None:
    edit = auto.find(ctrl_type='EditControl', depth=15)
if edit is None:
    raise RuntimeError('未找到输入框,请先跑示例 1 看控件树')

print('准备输入…')
auto.input('你好', ctrl=edit, paste=True)   # 中文务必 paste=True
auto.enter(edit)

# 等价一步写法(能定位到输入框时):
# auto.send_msg('你好', aid='chat_input')
# auto.send_msg('你好', ctrl_type='EditControl')

示例 4:组合键(全选 / 复制 / 粘贴)

用途:需要 Ctrl+A / C / V 时。推荐 hotkey,不要用 post 模式硬写 {Ctrl}a

auto = bind_auto()

# 虚拟键:0x11=Ctrl,0x41=A,0x43=C,0x56=V
auto.hotkey(0x11, 0x41)   # Ctrl+A 全选
auto.hotkey(0x11, 0x43)   # Ctrl+C 复制
text = auto.get_clip()
print('剪贴板内容:', text)

auto.set_clip('新内容')
auto.hotkey(0x11, 0x56)   # Ctrl+V 粘贴
print('已粘贴「新内容」')

记事本可先 find 到编辑框再 auto.copy(edit),效果类似。


示例 5:读剪贴板图文(笔记 / 混排)

用途:笔记、图文混排:既要文字也要图片路径。

auto = bind_auto()

ctrl = auto.find(ctrl_type='EditControl', depth=20)
if not ctrl:
    raise RuntimeError('请先定位到要复制的区域控件')

result = auto.copy_content(ctrl, mode='uia')
print('=== 给人看的报告 ===')
print(result.get('report'))

print('=== 给程序用的 items ===')
for item in result.get('items') or []:
    # type 常见:text / image / file
    print(item.get('type'), '=>', item.get('content'))

只解析当前剪贴板(不先对控件复制):

clip = auto.inspect_clipboard()
print(clip.get('report'))
if clip.get('success'):
    for item in clip.get('items') or []:
        print(item['type'], item['content'])

示例 6:点开弹窗再读内容

用途:点击后弹出新窗口(笔记窗、详情窗),要操作新窗口而不是旧窗口。

auto = bind_auto()

# 改成你实际弹窗的 ClassName(可用软件枚举窗口,或 dump 后看)
POPUP_CLASSES = ['NoteWnd', 'Chrome_WidgetWin_0']

before = auto.snapshot_popups(POPUP_CLASSES)   # 点击前先快照
auto.click(name='某条消息', mode='uia')         # ← 改成真实 Name / 或传入 ctrl
popup_hwnd = auto.wait_popup(POPUP_CLASSES, before, timeout=5.0)

if not popup_hwnd:
    print('未出现弹窗:检查 ClassName、点击是否成功、超时是否太短')
else:
    print('新窗口 hwnd=', popup_hwnd)
    popup = WinAuto(popup_hwnd, mode='uia')
    popup.activate()
    time.sleep(0.3)
    body = popup.find(ctrl_type='EditControl', depth=25)
    if body:
        print(popup.copy_content(body, mode='uia').get('report'))
    popup.close_window()

也可用包级 snapshot_hwnds / wait_new_toplevel / read_note_window,见 辅助与许可


示例 7:找图并点击(需视觉依赖)

仅在 UIA 拿不到控件、只能靠图标时使用。

py -3 -m pip install -r winautox/requirements_vision.txt
from winautox import WinAuto

# 先看环境
print(WinAuto.vision_status())

# region = (屏幕左上角 x, y, 宽, 高);先用截图工具量好再填
ok = WinAuto.click_pic('btn.png', (100, 200, 400, 300), sim=0.9)
print('点击成功' if ok else '未找到图片:检查路径、region、相似度 sim')

pos = WinAuto.findcolor('FF0000', (0, 0, 800, 600))
print('红色像素位置', pos)

texts = WinAuto.ocr((68, 81, 240, 200))
print('OCR 结果', texts)

更多:找图找色采样


示例 8:注册控件别名(少写重复参数)

用途:同一个输入框/按钮要操作很多次时,起个短名字。

auto = bind_auto()

auto.register('input', ctrl_type='EditControl', aid='chat_input', depth=15)
auto.register('send', ctrl_type='ButtonControl', name='发送', depth=15)

auto.input_cfg('input', 'hi')     # 等价于对别名对应控件 input
auto.click_cfg('send')

# 链式写法
auto.use('input').click().input('第二句').enter()

详见 控件别名


示例 9:拟人点击(更像真人移动鼠标)

auto = bind_auto(mode='uia')

btn = auto.find(name='确定')  # ← 改成真实按钮
if not btn:
    print('先 dump 找到按钮 Name')
else:
    # 曲线移动过去再点;range_x/y 让落点稍微抖动
    auto.human_click(btn, duration=0.4, hold=0.08, range_x=2, range_y=2)
    print('拟人点击完成')

详见 拟人操作


示例 10:把控件滚进可见区域再点

用途:虚拟列表里项在屏幕外,直接 click 会失败。

auto = bind_auto()

item = auto.find(ctrl_type='ListItemControl', name='某项名称', depth=20)
if not item:
    print('视口里没有该项,可能需要先滚动列表')
else:
    auto.scroll_into_view(item)
    time.sleep(0.2)
    auto.click(item, mode='uia')

详见 滚动与窗口


接下来

文档内容
方法手册总览全部分类方法索引
调试与示例更多组合套路
常见问题报错对照

上一页快速开始 · 下一页 WinAuto 总览