255 lines
11 KiB
Python
255 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Win32 元素定位:解析影刀 selectors.xml,按「类名 + 同类序号」逐层查找控件。
|
||
|
||
影刀 Win32 选择器本质就是控件树路径(用 Inspect 抓的),例如:
|
||
Window(cls=TfrmCompMgrMerge, title=社保费管理客户端)
|
||
> Pane(cls=TJdlsPanel, index=2)
|
||
> ... > Edit(cls=TITSEdit, index=0)
|
||
|
||
用 FindWindow / FindWindowEx 逐层下钻即可定位,**不需要 UIA**(老 Delphi/VB 客户端
|
||
根本没有 UIA 树,但 Win32 控件层次是完整的),稳定性和速度都优于图像识别。
|
||
|
||
接口:
|
||
lib = Selectors(xml_path)
|
||
lib.names() # 全部元素名
|
||
lib.find("税号输入框") # → hwnd(找不到抛 RuntimeError)
|
||
lib.exists("滑动栏") # → bool
|
||
lib.set_value("税号输入框", "91500...") # WM_SETTEXT,失败自动回退 点击+粘贴
|
||
lib.get_value("密码框") # → str
|
||
lib.click("确认单位") # 鼠标点控件中心
|
||
lib.screenshot("待选账户", path) # 控件截图(给 OCR 用)
|
||
lib.drag("滑动栏", dx=280) # 滑块拖动(验证码)
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ctypes
|
||
import os
|
||
import time
|
||
import xml.etree.ElementTree as ET
|
||
from typing import Dict, List, Optional, Union
|
||
|
||
try:
|
||
import win32con
|
||
import win32gui
|
||
except ImportError as _e: # pragma: no cover
|
||
raise RuntimeError("缺少依赖 pywin32,请安装:pip install pywin32") from _e
|
||
|
||
from ..config import logger
|
||
|
||
WM_SETTEXT = win32con.WM_SETTEXT
|
||
WM_GETTEXT = win32con.WM_GETTEXT
|
||
WM_GETTEXTLENGTH = win32con.WM_GETTEXTLENGTH
|
||
|
||
|
||
class Selectors:
|
||
"""影刀元素库(selectors.xml)的 Win32 实现。"""
|
||
|
||
def __init__(self, xml_path: str):
|
||
self.xml_path = xml_path
|
||
self._items: Dict[str, dict] = self._parse(xml_path)
|
||
|
||
# ---------- 解析 ----------
|
||
@staticmethod
|
||
def _parse(xml_path: str) -> Dict[str, dict]:
|
||
if not os.path.isfile(xml_path):
|
||
raise RuntimeError(f"元素库文件不存在:{xml_path}")
|
||
tree = ET.parse(xml_path)
|
||
items: Dict[str, dict] = {}
|
||
for el in tree.getroot().iter("selector"):
|
||
name = (el.get("name") or "").strip()
|
||
if not name:
|
||
continue
|
||
steps: List[dict] = []
|
||
for wnd in el.findall("wnd"):
|
||
opt = wnd.find("{*}optional")
|
||
index = None
|
||
raw_index = wnd.get("index")
|
||
if raw_index is not None:
|
||
try:
|
||
index = int(raw_index)
|
||
except ValueError:
|
||
index = None
|
||
if opt is not None and opt.get("index") is not None:
|
||
try:
|
||
index = int(opt.get("index"))
|
||
except ValueError:
|
||
pass
|
||
steps.append({
|
||
"cls": (wnd.get("cls") or "").strip(),
|
||
"title": (wnd.get("title") or "").strip(),
|
||
"index": index,
|
||
"optional": opt is not None,
|
||
})
|
||
items[name] = {
|
||
"name": name,
|
||
"win_title": (el.get("winTitle") or "").strip(),
|
||
"process": (el.get("processName") or "").strip(),
|
||
"steps": steps,
|
||
}
|
||
logger.info("元素库加载完成:%d 个元素(%s)", len(items), os.path.basename(xml_path))
|
||
return items
|
||
|
||
def names(self) -> List[str]:
|
||
return list(self._items.keys())
|
||
|
||
def describe(self, name: str) -> dict:
|
||
return dict(self._items.get(name) or {})
|
||
|
||
def _get(self, name: str) -> dict:
|
||
item = self._items.get(name)
|
||
if not item:
|
||
raise KeyError(f"元素库里没有「{name}」,可用元素:{', '.join(self.names())}")
|
||
return item
|
||
|
||
# ---------- 定位 ----------
|
||
@staticmethod
|
||
def _find_child(parent: int, cls: str, index: Optional[int]) -> int:
|
||
"""在 parent 下找第 index 个类名为 cls 的子窗口。"""
|
||
want = 0 if index is None else int(index)
|
||
seen = 0
|
||
after = 0
|
||
while True:
|
||
child = win32gui.FindWindowEx(parent, after, cls or None, None)
|
||
if not child:
|
||
return 0
|
||
if seen == want:
|
||
return child
|
||
seen += 1
|
||
after = child
|
||
|
||
def _resolve(self, item: dict, top_window: Optional[int] = None) -> int:
|
||
steps = item["steps"]
|
||
if not steps:
|
||
return 0
|
||
first = steps[0]
|
||
parent = int(top_window or 0)
|
||
if not parent:
|
||
parent = win32gui.FindWindow(first["cls"] or None, first["title"] or None)
|
||
if not parent and (first["title"] or item["win_title"]):
|
||
title = first["title"] or item["win_title"]
|
||
try:
|
||
from desktopauto import find_windows # 执行机预装依赖
|
||
cands = find_windows(title=title)
|
||
if not cands and item["process"]:
|
||
cands = find_windows(process=item["process"])
|
||
parent = int(cands[0]["hwnd"]) if cands else 0
|
||
except Exception: # noqa: BLE001
|
||
parent = 0
|
||
if not parent:
|
||
return 0
|
||
|
||
for step in steps[1:]:
|
||
child = self._find_child(parent, step["cls"], step["index"])
|
||
if not child:
|
||
if step["optional"]:
|
||
continue # 影刀语义:该层可选,找不到就跳过这一层继续下钻
|
||
return 0
|
||
parent = child
|
||
return parent
|
||
|
||
def find(self, name: str, top_window: Optional[int] = None,
|
||
timeout: float = 0.0, interval: float = 0.2) -> int:
|
||
"""定位元素,返回 hwnd;timeout>0 时轮询等待,超时抛错。"""
|
||
item = self._get(name)
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
hwnd = self._resolve(item, top_window)
|
||
if hwnd:
|
||
return hwnd
|
||
if time.time() >= deadline:
|
||
raise RuntimeError(
|
||
f"未定位到元素「{name}」(客户端是否已启动/界面是否已切到目标页?)")
|
||
time.sleep(max(0.05, interval))
|
||
|
||
def exists(self, name: str, top_window: Optional[int] = None) -> bool:
|
||
try:
|
||
return bool(self._resolve(self._get(name), top_window))
|
||
except KeyError:
|
||
return False
|
||
|
||
# ---------- 操作 ----------
|
||
@staticmethod
|
||
def _rect(hwnd: int):
|
||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||
return left, top, right, bottom
|
||
|
||
def center(self, name: str, top_window: Optional[int] = None) -> tuple:
|
||
left, top, right, bottom = self._rect(self.find(name, top_window))
|
||
return (left + right) // 2, (top + bottom) // 2
|
||
|
||
def get_value(self, name: str, top_window: Optional[int] = None) -> str:
|
||
"""读控件文本(WM_GETTEXT)。"""
|
||
hwnd = self.find(name, top_window)
|
||
length = int(win32gui.SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0) or 0)
|
||
buf = ctypes.create_unicode_buffer(max(1, length + 1))
|
||
win32gui.SendMessage(hwnd, WM_GETTEXT, max(1, length + 1), buf)
|
||
return buf.value
|
||
|
||
def set_value(self, name: str, text: str, top_window: Optional[int] = None,
|
||
timeout: float = 5.0, verify: bool = True) -> bool:
|
||
"""给输入框赋值:优先 WM_SETTEXT(快、不受焦点影响),无效时回退 点击+粘贴。
|
||
|
||
Returns:
|
||
True=WM_SETTEXT 成功;False=走了回退路径(点击+粘贴)。
|
||
"""
|
||
hwnd = self.find(name, top_window, timeout=timeout)
|
||
text = "" if text is None else str(text)
|
||
try:
|
||
win32gui.SendMessage(hwnd, WM_SETTEXT, 0, text)
|
||
except Exception as e: # noqa: BLE001
|
||
logger.warning("WM_SETTEXT 失败(%s),改用点击+粘贴", e)
|
||
self._type_into(hwnd, text)
|
||
return False
|
||
if verify:
|
||
got = self.get_value(name, top_window)
|
||
if got.strip() != text.strip():
|
||
logger.warning("WM_SETTEXT 未生效(读到「%s」),改用点击+粘贴", got)
|
||
self._type_into(hwnd, text)
|
||
return False
|
||
return True
|
||
|
||
@staticmethod
|
||
def _type_into(hwnd: int, text: str) -> None:
|
||
"""回退方案:点控件中心 → Ctrl+A → 粘贴(中文/长文本安全)。"""
|
||
from desktopauto import click_at, hotkey, paste
|
||
left, top, right, bottom = Selectors._rect(hwnd)
|
||
cx, cy = (left + right) // 2, (top + bottom) // 2
|
||
try:
|
||
win32gui.SetForegroundWindow(hwnd)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
click_at(cx, cy)
|
||
time.sleep(0.15)
|
||
hotkey("ctrl", "a")
|
||
paste(text)
|
||
|
||
def click(self, name: str, top_window: Optional[int] = None,
|
||
timeout: float = 5.0, delay_after: float = 0.3) -> None:
|
||
"""点击控件中心(鼠标真实点击,兼容自绘控件)。"""
|
||
from desktopauto import click_at
|
||
hwnd = self.find(name, top_window, timeout=timeout)
|
||
left, top, right, bottom = self._rect(hwnd)
|
||
cx, cy = (left + right) // 2, (top + bottom) // 2
|
||
click_at(cx, cy)
|
||
if delay_after:
|
||
time.sleep(float(delay_after))
|
||
logger.debug("点击元素「%s」→ (%d, %d)", name, cx, cy)
|
||
|
||
def screenshot(self, name: str, path: str = "",
|
||
top_window: Optional[int] = None) -> str:
|
||
"""截控件区域(给 OCR / 元素识别留档用),返回图片路径。"""
|
||
from desktopauto import screenshot as _shot
|
||
hwnd = self.find(name, top_window)
|
||
left, top, right, bottom = self._rect(hwnd)
|
||
return _shot(path, region=(left, top, right, bottom))
|
||
|
||
def drag(self, name: str, dx: int = 0, dy: int = 0, duration: float = 0.8,
|
||
top_window: Optional[int] = None) -> None:
|
||
"""拖动控件(滑块验证码:对「滑动栏」向右拖 dx 像素)。"""
|
||
from desktopauto import drag as _drag
|
||
hwnd = self.find(name, top_window)
|
||
left, top, right, bottom = self._rect(hwnd)
|
||
sx, sy = (left + right) // 2, (top + bottom) // 2
|
||
_drag((sx, sy), (sx + int(dx), sy + int(dy)), duration=duration)
|
||
logger.debug("拖动元素「%s」→ 偏移 (%d, %d)", name, dx, dy)
|