Files
37duAutomation/libs/desktopauto/desktopauto/_win32.py
T

512 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Windows 底层封装:DPI 感知、窗口枚举/矩形/激活、鼠标点击。
全部走 ctypes,不引入 pywin32 / pyautogui,保证「装完 opencv + pillow 就能跑」。
非 Windows 平台调用会直接抛错(本库只面向 Windows 执行机)。
"""
from __future__ import annotations
import ctypes
import os
import sys
import time
from ctypes import wintypes
from typing import List, Optional, Tuple, Union
IS_WINDOWS = sys.platform.startswith("win")
SW_RESTORE = 9
DWMWA_EXTENDED_FRAME_BOUNDS = 9
# mouse_event 标志位
MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
MOUSEEVENTF_RIGHTDOWN = 0x0008
MOUSEEVENTF_RIGHTUP = 0x0010
MOUSEEVENTF_MIDDLEDOWN = 0x0020
MOUSEEVENTF_MIDDLEUP = 0x0040
_BUTTON_FLAGS = {
"left": (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),
"right": (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),
"middle": (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),
}
_DPI_READY = False
def require_windows(what: str) -> None:
if not IS_WINDOWS:
raise RuntimeError(f"{what} 仅支持 Windows(当前平台:{sys.platform})")
def ensure_dpi_aware() -> None:
"""声明进程 DPI 感知(幂等)。
不做这一步,系统缩放 125%/150% 时截图按逻辑像素返回、SetCursorPos 按物理像素生效,
两边差一个缩放系数,会出现「图明明在屏幕上,点击却偏了几十像素」。
"""
global _DPI_READY
if _DPI_READY:
return
if IS_WINDOWS:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # PER_MONITOR_DPI_AWARE_V2
except Exception: # noqa: BLE001 老系统(Win7/8)回退
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception: # noqa: BLE001
pass
_DPI_READY = True
# ==================== 窗口 ====================
def list_windows(keyword: str = "", visible_only: bool = True) -> List[Tuple[int, str]]:
"""按标题关键字模糊查找顶层窗口,返回 [(hwnd, title)](已排除最小化窗口)。"""
require_windows("窗口查找")
ensure_dpi_aware()
user32 = ctypes.windll.user32
found: List[Tuple[int, str]] = []
keyword = (keyword or "").strip()
buf = ctypes.create_unicode_buffer(512)
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
def _enum(hwnd, _lparam): # noqa: ANN001
if visible_only and not user32.IsWindowVisible(hwnd):
return True
if user32.IsIconic(hwnd): # 最小化:截图会是空白,直接排除
return True
buf.value = ""
user32.GetWindowTextW(hwnd, buf, 512)
title = buf.value.strip()
if not title:
return True
if keyword and keyword not in title:
return True
found.append((int(hwnd), title))
return True
user32.EnumWindows(_enum, 0)
return found
def resolve_hwnd(window: Union[int, str]) -> int:
"""把 hwnd 或标题关键字解析为唯一 hwnd(多个命中取标题最短的主窗口)。"""
if isinstance(window, int):
return window
hits = list_windows(str(window))
if not hits:
raise RuntimeError(f"未找到标题含「{window}」的可见窗口(窗口是否已打开/最小化?)")
if len(hits) > 1:
hits.sort(key=lambda x: len(x[1]))
hits = [hits[0]]
return hits[0][0]
def window_rect(window: Union[int, str]) -> Tuple[int, int, int, int]:
"""窗口屏幕矩形 (left, top, right, bottom),优先用 DWM 扩展边框(更贴近可见区域)。"""
require_windows("窗口截图")
ensure_dpi_aware()
hwnd = resolve_hwnd(window)
rect = wintypes.RECT()
try:
hr = ctypes.windll.dwmapi.DwmGetWindowAttribute(
wintypes.HWND(hwnd), wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
ctypes.byref(rect), ctypes.sizeof(rect))
if hr != 0:
raise OSError(hr)
except Exception: # noqa: BLE001 DWM 不可用时回退
if not ctypes.windll.user32.GetWindowRect(wintypes.HWND(hwnd), ctypes.byref(rect)):
raise RuntimeError(f"获取窗口矩形失败:{window}")
if rect.right <= rect.left or rect.bottom <= rect.top:
raise RuntimeError(f"窗口矩形无效(可能已最小化):{window}")
return int(rect.left), int(rect.top), int(rect.right), int(rect.bottom)
def activate_window(window: Union[int, str], wait: float = 0.2) -> int:
"""前置并激活窗口,返回 hwnd(点击前建议先激活,避免点到被遮挡的位置)。"""
hwnd = resolve_hwnd(window)
user32 = ctypes.windll.user32
try:
user32.ShowWindow(wintypes.HWND(hwnd), SW_RESTORE)
user32.SetForegroundWindow(wintypes.HWND(hwnd))
except Exception: # noqa: BLE001 前台切换可能被系统策略拒绝,不影响后续截图/点击
pass
if wait:
time.sleep(wait)
return hwnd
# ==================== 鼠标 ====================
def move_to(x: int, y: int, settle: float = 0.0) -> None:
"""移动鼠标到屏幕物理像素坐标。"""
require_windows("鼠标操作")
ensure_dpi_aware()
if not ctypes.windll.user32.SetCursorPos(int(x), int(y)):
raise RuntimeError(f"鼠标移动失败:({x}, {y})")
if settle:
time.sleep(settle)
MOVE_SPEEDS = {"instant": 0.0, "fast": 0.05, "middle": 0.15, "normal": 0.15, "slow": 0.35}
def move_mouse(x: int, y: int, relative_to: str = "screen",
speed: str = "instant", window: Union[int, str, None] = None) -> Tuple[int, int]:
"""移动鼠标(影刀「移动鼠标」指令)。
Args:
x, y: 目标坐标(相对屏幕,或相对窗口左上角)。
relative_to: "screen"(默认)或 "window"(需传 window)。
speed: instant / fast / middle / slow(非 instant 时分步移动,模拟人工轨迹)。
window: relative_to="window" 时的窗口(hwnd 或标题)。
Returns:
实际移动到的屏幕坐标 (x, y)。
"""
require_windows("鼠标移动")
ensure_dpi_aware()
if (relative_to or "screen").lower() == "window":
if window is None:
raise ValueError('relative_to="window" 时必须传 window')
left, top, _right, _bottom = window_rect(window)
x, y = int(x) + left, int(y) + top
else:
x, y = int(x), int(y)
duration = MOVE_SPEEDS.get((speed or "instant").lower(), 0.0)
if duration <= 0:
move_to(x, y)
return x, y
sx, sy = cursor_pos()
steps = max(6, int(duration / 0.01))
for i in range(1, steps + 1):
t = i / steps
move_to(round(sx + (x - sx) * t), round(sy + (y - sy) * t))
time.sleep(duration / steps)
return x, y
def click_at(x: int, y: int, button: str = "left", clicks: int = 1,
interval: float = 0.05, settle: float = 0.05) -> None:
"""在屏幕坐标点击(先移动再按下/抬起),支持左/右/中键与连击。"""
require_windows("鼠标点击")
button = (button or "left").lower()
if button not in _BUTTON_FLAGS:
raise ValueError(f"不支持的鼠标键:{button}(可选 left/right/middle)")
down, up = _BUTTON_FLAGS[button]
move_to(x, y)
if settle:
time.sleep(settle)
user32 = ctypes.windll.user32
for i in range(max(1, int(clicks))):
user32.mouse_event(down, 0, 0, 0, 0)
time.sleep(0.01)
user32.mouse_event(up, 0, 0, 0, 0)
if i < clicks - 1:
time.sleep(max(0.01, interval))
def cursor_pos() -> Tuple[int, int]:
"""当前鼠标屏幕坐标。"""
require_windows("鼠标坐标读取")
ensure_dpi_aware()
pt = wintypes.POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))
return int(pt.x), int(pt.y)
# ==================== 滚轮 / 拖拽 ====================
MOUSEEVENTF_WHEEL = 0x0800
MOUSEEVENTF_HWHEEL = 0x1000
WHEEL_DELTA = 120
def scroll(notches: int = 3, at: Optional[Tuple[int, int]] = None,
horizontal: bool = False, settle: float = 0.08) -> None:
"""滚轮滚动。notches>0 向上(垂直)/向左(水平),<0 反之;at 指定先移动到的坐标(不传=当前位置)。"""
require_windows("滚轮滚动")
ensure_dpi_aware()
if at is not None:
move_to(int(at[0]), int(at[1]))
if settle:
time.sleep(settle)
flag = MOUSEEVENTF_HWHEEL if horizontal else MOUSEEVENTF_WHEEL
delta = ctypes.c_ulong((int(notches) * WHEEL_DELTA) & 0xFFFFFFFF).value
ctypes.windll.user32.mouse_event(flag, 0, 0, delta, 0)
def drag(from_xy: Tuple[int, int], to_xy: Tuple[int, int],
duration: float = 0.5, button: str = "left", steps: int = 0) -> None:
"""按住鼠标从 from_xy 拖到 to_xy(分步移动,模拟人工拖动轨迹)。"""
require_windows("鼠标拖拽")
button = (button or "left").lower()
if button not in _BUTTON_FLAGS:
raise ValueError(f"不支持的鼠标键:{button}(可选 left/right/middle)")
down, up = _BUTTON_FLAGS[button]
x0, y0 = int(from_xy[0]), int(from_xy[1])
x1, y1 = int(to_xy[0]), int(to_xy[1])
total = max(8, int(steps) if steps else int(max(0.05, duration) / 0.01))
user32 = ctypes.windll.user32
move_to(x0, y0)
time.sleep(0.05)
user32.mouse_event(down, 0, 0, 0, 0)
try:
for i in range(1, total + 1):
t = i / total
move_to(round(x0 + (x1 - x0) * t), round(y0 + (y1 - y0) * t))
time.sleep(max(0.005, duration / total))
finally:
time.sleep(0.05)
user32.mouse_event(up, 0, 0, 0, 0)
# ==================== 窗口信息 / 进程 ====================
def _process_name(pid: int) -> str:
"""按进程 ID 取可执行文件名(如 DingTalk.exe);失败返回空串。"""
if not pid:
return ""
kernel32 = ctypes.windll.kernel32
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
kernel32.QueryFullProcessImageNameW.argtypes = [
ctypes.c_void_p, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
if not handle:
return ""
try:
buf = ctypes.create_unicode_buffer(1024)
size = wintypes.DWORD(1024)
if kernel32.QueryFullProcessImageNameW(handle, 0, buf, ctypes.byref(size)):
return os.path.basename(buf.value)
return ""
finally:
kernel32.CloseHandle(ctypes.c_void_p(handle))
def _window_pid(hwnd: int) -> int:
user32 = ctypes.windll.user32
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(wintypes.HWND(hwnd), ctypes.byref(pid))
return int(pid.value)
def _window_class(hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(256)
ctypes.windll.user32.GetClassNameW(wintypes.HWND(hwnd), buf, 256)
return buf.value
def _window_title(hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(512)
ctypes.windll.user32.GetWindowTextW(wintypes.HWND(hwnd), buf, 512)
return buf.value.strip()
def _window_rect_raw(hwnd: int) -> Tuple[int, int, int, int]:
rect = wintypes.RECT()
if not ctypes.windll.user32.GetWindowRect(wintypes.HWND(hwnd), ctypes.byref(rect)):
return 0, 0, 0, 0
return int(rect.left), int(rect.top), int(rect.right), int(rect.bottom)
def window_info(hwnd: int, with_process: bool = True) -> dict:
"""取窗口完整信息:{hwnd, title, class_name, pid, process, rect, minimized, visible}。"""
require_windows("窗口信息")
ensure_dpi_aware()
user32 = ctypes.windll.user32
pid = _window_pid(hwnd)
return {
"hwnd": int(hwnd),
"title": _window_title(hwnd),
"class_name": _window_class(hwnd),
"pid": pid,
"process": _process_name(pid) if with_process else "",
"rect": _window_rect_raw(hwnd),
"minimized": bool(user32.IsIconic(wintypes.HWND(hwnd))),
"visible": bool(user32.IsWindowVisible(wintypes.HWND(hwnd))),
}
def find_windows(title: str = "", exact: bool = False, pid: int = 0,
process: str = "", class_name: str = "",
visible_only: bool = True, include_minimized: bool = False,
with_process: bool = True) -> List[dict]:
"""按条件查找顶层窗口,返回窗口信息 dict 列表(按标题长度升序,主窗口在前)。
Args:
title: 标题过滤;exact=False 时包含匹配(默认),exact=True 完全相等。空=不过滤。
pid: 进程 ID 精确匹配(0=不过滤)。
process: 进程名过滤(如 "DingTalk.exe" / "DingTalk",不区分大小写、包含匹配)。
class_name: 窗口类名(包含匹配,如 "Chrome_WidgetWin_1")。
visible_only: 只看可见窗口。
include_minimized: 是否包含最小化窗口(默认排除,因为截图会是空白)。
with_process: 是否解析进程名(关掉可提速)。
"""
require_windows("窗口查找")
ensure_dpi_aware()
user32 = ctypes.windll.user32
out: List[dict] = []
title = (title or "").strip()
process_lc = (process or "").strip().lower()
class_name = (class_name or "").strip()
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
def _enum(hwnd, _lparam): # noqa: ANN001
if visible_only and not user32.IsWindowVisible(hwnd):
return True
if not include_minimized and user32.IsIconic(hwnd):
return True
t = _window_title(hwnd)
if title:
if exact:
if t != title:
return True
elif title not in t:
return True
if class_name and class_name not in _window_class(hwnd):
return True
w_pid = _window_pid(hwnd)
if pid and w_pid != int(pid):
return True
info = {
"hwnd": int(hwnd), "title": t, "class_name": _window_class(hwnd),
"pid": w_pid, "process": "", "rect": _window_rect_raw(hwnd),
"minimized": False, "visible": True,
}
if process_lc:
name = _process_name(w_pid) if with_process else ""
if process_lc not in name.lower():
return True
info["process"] = name
elif with_process:
info["process"] = _process_name(w_pid)
if not info["title"] and not class_name:
return True # 无标题的壳窗口,除非按类名找,否则跳过
out.append(info)
return True
user32.EnumWindows(_enum, 0)
out.sort(key=lambda w: len(w["title"]))
return out
def wait_window(title: str = "", timeout: float = 10.0, interval: float = 0.3,
**kwargs) -> Optional[dict]:
"""等待窗口出现(参数同 find_windows),超时返回 None。"""
deadline = time.time() + max(0.0, float(timeout))
while True:
wins = find_windows(title=title, **kwargs)
if wins:
return wins[0]
if time.time() >= deadline:
return None
time.sleep(max(0.05, float(interval)))
# ==================== 窗口操作(Window 对象用) ====================
SW_MINIMIZE = 6
SW_MAXIMIZE = 3
WM_CLOSE = 0x0010
def is_window(hwnd: int) -> bool:
"""句柄是否仍然有效(窗口没被关掉)。"""
return bool(ctypes.windll.user32.IsWindow(wintypes.HWND(int(hwnd))))
def foreground_hwnd() -> int:
"""当前前台窗口句柄(0 = 没有)。"""
return int(ctypes.windll.user32.GetForegroundWindow() or 0)
def is_foreground(hwnd: int) -> bool:
"""该窗口是否在前台。"""
return foreground_hwnd() == int(hwnd)
def show_window(hwnd: int, cmd: int) -> None:
ctypes.windll.user32.ShowWindow(wintypes.HWND(int(hwnd)), cmd)
def minimize_window(hwnd: int) -> None:
show_window(hwnd, SW_MINIMIZE)
def maximize_window(hwnd: int) -> None:
show_window(hwnd, SW_MAXIMIZE)
def restore_window(hwnd: int) -> None:
show_window(hwnd, SW_RESTORE)
def close_window(hwnd: int, wait: float = 0.0) -> None:
"""发送关闭消息(等同点右上角 ×;应用可能弹「是否保存」确认框)。"""
ctypes.windll.user32.PostMessageW(wintypes.HWND(int(hwnd)), WM_CLOSE, 0, 0)
if wait:
time.sleep(wait)
PROCESS_TERMINATE = 0x0001
def terminate_process(pid: int, wait: float = 0.5) -> None:
"""强制结束进程(TerminateProcess)。会杀掉该进程的所有窗口,数据可能丢失,慎用。"""
require_windows("结束进程")
kernel32 = ctypes.windll.kernel32
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
handle = kernel32.OpenProcess(PROCESS_TERMINATE, False, int(pid))
if not handle:
raise RuntimeError(f"无法结束进程 {pid}(权限不足,或进程已退出)")
try:
if not kernel32.TerminateProcess(ctypes.c_void_p(handle), 1):
raise RuntimeError(f"TerminateProcess 调用失败:进程 {pid}")
finally:
kernel32.CloseHandle(ctypes.c_void_p(handle))
if wait:
time.sleep(wait)
def move_window(hwnd: int, x: int, y: int,
width: Optional[int] = None, height: Optional[int] = None) -> None:
"""移动窗口(不传宽高则保持原尺寸)。"""
left, top, right, bottom = _window_rect_raw(hwnd)
w = int(width) if width else max(1, right - left)
h = int(height) if height else max(1, bottom - top)
ctypes.windll.user32.MoveWindow(wintypes.HWND(int(hwnd)), int(x), int(y), w, h, True)
def child_windows(window: Union[int, str], with_process: bool = False) -> List[dict]:
"""列出子窗口(hwnd/类名/标题/矩形),找弹窗、内嵌控件时用。"""
require_windows("子窗口枚举")
ensure_dpi_aware()
hwnd = resolve_hwnd(window)
user32 = ctypes.windll.user32
out: List[dict] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
def _enum(child, _lparam): # noqa: ANN001
out.append({
"hwnd": int(child), "title": _window_title(child),
"class_name": _window_class(child), "pid": _window_pid(child),
"process": "", "rect": _window_rect_raw(child),
"minimized": False, "visible": bool(user32.IsWindowVisible(child)),
})
return True
user32.EnumChildWindows(wintypes.HWND(hwnd), _enum, 0)
return out
def screen_size() -> Tuple[int, int]:
"""主屏物理像素尺寸 (width, height)。"""
require_windows("屏幕尺寸读取")
ensure_dpi_aware()
user32 = ctypes.windll.user32
return int(user32.GetSystemMetrics(0)), int(user32.GetSystemMetrics(1))