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

327 lines
12 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 -*-
"""窗口相关 API(对外友好封装,底层在 _win32)。
用途:把识图范围限定到某个窗口,避免全屏里同款按钮/图标误命中;
点击前先激活窗口,避免点到被其它窗口遮挡的位置。
"""
from __future__ import annotations
import time
from typing import List, Optional, Tuple, Union
from ._win32 import activate_window as _activate
from ._win32 import child_windows as _children
from ._win32 import close_window as _close
from ._win32 import find_windows as _find
from ._win32 import foreground_hwnd as _foreground_hwnd
from ._win32 import is_foreground as _is_foreground
from ._win32 import is_window as _is_window
from ._win32 import list_windows as _list
from ._win32 import maximize_window as _maximize
from ._win32 import minimize_window as _minimize
from ._win32 import move_window as _move
from ._win32 import restore_window as _restore
from ._win32 import terminate_process as _terminate
from ._win32 import wait_window as _wait
from ._win32 import window_info as _info
from ._win32 import window_rect as _rect
__all__ = ["Window", "get_window", "foreground_window", "close_window",
"list_windows", "find_window", "find_windows", "wait_window",
"child_windows", "window_info", "window_rect", "activate_window"]
def list_windows(keyword: str = "", visible_only: bool = True) -> List[Tuple[int, str]]:
"""列出顶层窗口 [(hwnd, 标题)];keyword 非空时按标题模糊过滤。"""
return _list(keyword, visible_only)
def find_window(keyword: str) -> int:
"""按标题关键字找窗口,返回 hwnd;找不到抛错,多个命中取标题最短的主窗口。"""
hits = _list(keyword)
if not hits:
raise RuntimeError(f"未找到标题含「{keyword}」的可见窗口(窗口是否已打开/最小化?)")
hits.sort(key=lambda x: len(x[1]))
return hits[0][0]
def window_rect(window: Union[int, str]) -> Tuple[int, int, int, int]:
"""窗口屏幕矩形 (left, top, right, bottom)。window 可为 hwnd 或标题关键字。"""
return _rect(window)
def find_windows(title: str = "", exact: bool = False, pid: int = 0,
process: str = "", class_name: str = "",
visible_only: bool = True, include_minimized: bool = False) -> List[dict]:
"""多条件查找窗口(标题/进程/PID/类名),返回窗口信息列表(主窗口在前)。
比 list_windows 强的地方:能区分「两个钉钉」「标题带文件名」这类情况,
例如 find_windows(process="DingTalk.exe")、find_windows(title="工资卡", exact=True)。
"""
return _find(title=title, exact=exact, pid=pid, process=process,
class_name=class_name, visible_only=visible_only,
include_minimized=include_minimized)
def wait_window(title: str = "", timeout: float = 10.0, interval: float = 0.3,
**kwargs) -> Optional[dict]:
"""等窗口出现(参数同 find_windows),超时返回 None。"""
return _wait(title=title, timeout=timeout, interval=interval, **kwargs)
def window_info(hwnd: int) -> dict:
"""单个窗口的完整信息(标题/类名/PID/进程名/矩形/是否最小化)。"""
return _info(hwnd)
def child_windows(window: Union[int, str]) -> List[dict]:
"""列出窗口的子窗口(找内嵌控件、弹层时用)。"""
return _children(window)
# ==================== 窗口对象 ====================
class Window:
"""窗口对象:一次拿到,后面反复用(激活/关闭/移动/截图/子窗口/绑定 Screen)。
```python
w = get_window(process="DingTalk.exe")
w.activate()
print(w.title, w.rect, w.pid)
w.screen(threshold=0.9).click("img/btn.png") # 直接拿到绑定该窗口的 Screen
w.close()
```
说明:`rect` 用 DWM 扩展边框(与截图/点击坐标一致),比 `GetWindowRect` 少几像素阴影。
"""
def __init__(self, hwnd: int):
hwnd = int(hwnd)
if not _is_window(hwnd):
raise RuntimeError(f"窗口句柄无效:{hwnd}(窗口可能已关闭)")
self._hwnd = hwnd
# ---------- 基础信息(实时读取,窗口关了会抛错) ----------
@property
def hwnd(self) -> int:
return self._hwnd
@property
def title(self) -> str:
return _info(self._hwnd)["title"]
@property
def class_name(self) -> str:
return _info(self._hwnd)["class_name"]
@property
def pid(self) -> int:
return _info(self._hwnd)["pid"]
@property
def process(self) -> str:
return _info(self._hwnd)["process"]
@property
def rect(self) -> Tuple[int, int, int, int]:
"""(left, top, right, bottom),DWM 扩展边框,与截图/点击坐标一致。"""
return _rect(self._hwnd)
@property
def left(self) -> int:
return self.rect[0]
@property
def top(self) -> int:
return self.rect[1]
@property
def width(self) -> int:
left, _top, right, _bottom = self.rect
return max(0, right - left)
@property
def height(self) -> int:
_left, top, _right, bottom = self.rect
return max(0, bottom - top)
@property
def center(self) -> Tuple[int, int]:
return self.left + self.width // 2, self.top + self.height // 2
@property
def minimized(self) -> bool:
return bool(_info(self._hwnd)["minimized"])
@property
def visible(self) -> bool:
return bool(_info(self._hwnd)["visible"])
def info(self) -> dict:
"""完整信息 dict(title/class_name/pid/process/rect/minimized/visible)。"""
return _info(self._hwnd)
def exists(self) -> bool:
"""窗口是否还在(关闭后返回 False,不会抛错)。"""
return _is_window(self._hwnd)
def __repr__(self) -> str:
try:
return f"<Window hwnd={self._hwnd} '{self.title}' {self.width}x{self.height}>"
except Exception: # noqa: BLE001
return f"<Window hwnd={self._hwnd} (已失效)>"
# ---------- 操作 ----------
def activate(self) -> "Window":
"""激活到前台(还原最小化 + 置前),返回自身便于链式调用。"""
_activate(self._hwnd)
return self
def is_foreground(self) -> bool:
"""当前是否在前台。"""
return _is_foreground(self._hwnd)
def minimize(self) -> "Window":
_minimize(self._hwnd)
return self
def maximize(self) -> "Window":
_maximize(self._hwnd)
return self
def restore(self) -> "Window":
_restore(self._hwnd)
return self
def move(self, x: int, y: int,
width: Optional[int] = None, height: Optional[int] = None) -> "Window":
"""移动窗口;不传宽高保持原尺寸。"""
_move(self._hwnd, x, y, width, height)
return self
def close(self, wait: float = 0.5) -> None:
"""关闭窗口(等同点 ×,可能弹「是否保存」确认框);只是发消息,不保证已退出。"""
_close(self._hwnd, wait=wait)
def kill(self, wait: float = 0.5) -> None:
"""强制结束该窗口所属进程(TerminateProcess):应用无响应/有确认弹框时用。
注意:杀掉的是整个进程,该应用的所有窗口都会消失,未保存数据会丢。
"""
_terminate(self.pid, wait=wait)
def wait_closed(self, timeout: float = 10.0, interval: float = 0.3) -> bool:
"""等待窗口关闭,超时返回 False。"""
deadline = time.time() + max(0.0, float(timeout))
while True:
if not self.exists():
return True
if time.time() >= deadline:
return False
time.sleep(max(0.05, float(interval)))
def wait_ready(self, timeout: float = 10.0, interval: float = 0.3) -> bool:
"""等待窗口可见且非最小化(启动软件后等它出来),超时返回 False。"""
deadline = time.time() + max(0.0, float(timeout))
while True:
if self.exists():
info = self.info()
if info["visible"] and not info["minimized"]:
return True
if time.time() >= deadline:
return False
time.sleep(max(0.05, float(interval)))
def children(self) -> List[dict]:
"""子窗口列表(内嵌控件/弹层)。"""
return _children(self._hwnd)
def screenshot(self, path: str = "") -> str:
"""只截这个窗口(含窗口外框区域的实际屏幕内容)。"""
from . import capture # 延迟导入,避免循环依赖
return capture.screenshot(path=path, window=self._hwnd)
def screen(self, **kwargs):
"""拿到绑定本窗口的 Screen(识图/OCR/点击都会限定在这个窗口内)。
```python
w = get_window(process="DingTalk.exe")
s = w.screen(threshold=0.9, debug_dir="debug")
s.click("img/btn_send.png")
```
"""
from .screen import Screen # 延迟导入,避免循环依赖
kwargs.setdefault("activate_before_click", True)
return Screen(window=self._hwnd, **kwargs)
def to_dict(self) -> dict:
info = _info(self._hwnd)
info["rect"] = list(self.rect)
return info
def get_window(title: str = "", exact: bool = False, pid: int = 0,
process: str = "", class_name: str = "", index: int = 0,
timeout: float = 0.0) -> Window:
"""获取窗口对象(RPA 的「获取窗口对象」)。
Args:
title: 标题(exact=False 包含匹配)。
process: 进程名,如 "DingTalk.exe"。
pid: 进程 ID。
class_name: 窗口类名。
index: 同名/同进程多个窗口时取第几个(0=主窗口,因为结果按标题长度排序)。
timeout: >0 时轮询等待窗口出现(秒)。
Raises:
RuntimeError: 找不到窗口(或超时)。
"""
if timeout and timeout > 0:
win = _wait(title=title, timeout=timeout, exact=exact, pid=pid,
process=process, class_name=class_name)
if not win:
raise RuntimeError(
f"等待窗口超时({timeout}s):title={title!r} process={process!r} pid={pid}")
return Window(win["hwnd"])
wins = _find(title=title, exact=exact, pid=pid, process=process, class_name=class_name)
if not wins:
raise RuntimeError(
f"未找到窗口:title={title!r} process={process!r} pid={pid} class_name={class_name!r}"
f"(窗口是否已打开?最小化窗口默认不列出)")
if index < 0 or index >= len(wins):
raise RuntimeError(f"窗口下标越界:index={index},共找到 {len(wins)} 个窗口")
return Window(wins[index]["hwnd"])
def foreground_window() -> Optional[Window]:
"""当前前台窗口对象(没有则返回 None)。"""
hwnd = _foreground_hwnd()
if not hwnd or not _is_window(hwnd):
return None
return Window(hwnd)
def activate_window(window_or_title: Union[int, str, Window]) -> int:
"""激活软件窗口(RPA 的「激活软件窗口」):hwnd / 标题 / Window 对象都可以。"""
if isinstance(window_or_title, Window):
return _activate(window_or_title.hwnd)
return _activate(window_or_title)
def close_window(window_or_title: Union[int, str, Window], wait: float = 0.5) -> None:
"""关闭软件窗口(RPA 的「关闭软件窗口」):hwnd / 标题 / Window 对象都可以。
发 WM_CLOSE(等同点 ×),应用若弹「是否保存」需要你再处理;
要确保一定关掉,用 `w.kill()` 或 `w.close()` 后再 `w.wait_closed()`。
"""
if isinstance(window_or_title, Window):
hwnd = window_or_title.hwnd
elif isinstance(window_or_title, int):
hwnd = window_or_title
else:
hwnd = find_window(window_or_title)
_close(hwnd, wait=wait)