有多个目标符合 怎么处理
时间: 2024-03-16 21:42:29 浏览: 10
如果有多个符合条件的窗口,可以通过判断窗口的屏幕位置来确定哪个窗口是需要的。通常情况下,符合条件的窗口位置是不完全相同的,可以通过比较位置来确定需要的窗口。
以下是示例代码:
```python
import win32api
import win32con
import win32gui
def find_window_by_title(handle, title):
def callback(hwnd, hwnds):
if win32gui.IsWindowVisible(hwnd) and title in win32gui.GetWindowText(hwnd):
hwnds.append(hwnd)
return True
hwnds = []
win32gui.EnumChildWindows(handle, callback, hwnds)
return hwnds
def click_window_center(hwnd):
x1, y1, x2, y2 = win32gui.GetWindowRect(hwnd)
x = (x1 + x2) // 2
y = (y1 + y2) // 2
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
# 查找指定句柄下符合标题的窗口
handle = 123456 # 指定句柄
title = "窗口标题"
hwnds = find_window_by_title(handle, title)
if hwnds:
# 获取窗口类名和位置
targets = []
for hwnd in hwnds:
class_name = win32gui.GetClassName(hwnd)
x1, y1, x2, y2 = win32gui.GetWindowRect(hwnd)
targets.append((hwnd, class_name, (x1, y1, x2, y2)))
# 根据位置排序,选择需要的窗口
targets.sort(key=lambda x: x[2])
target = targets[0]
# 点击窗口中心点
click_window_center(target[0])
print(f"句柄:{target[0]},类名:{target[1]},位置:{target[2]}")
else:
print("未找到符合条件的窗口")
```
以上代码会返回所有符合条件的窗口的句柄、类名和位置,并根据位置排序,选择位置最小的窗口,并点击其中心点。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)