我正在尝试在 Windows 10 上编写一个 Python 脚本,通过标题查找窗口,然后使用 pywin32 移动/调整其大小。我有以下代码:
import win32gui
# Global variables
found_hwnd = None
partial_title = None # We'll set this before calling EnumWindows
def enum_windows_callback(hwnd, lParam):
global found_hwnd, partial_title
if win32gui.IsWindowVisible(hwnd):
window_title = win32gui.GetWindowText(hwnd)
if partial_title and partial_title.lower() in window_title.lower():
found_hwnd = hwnd
# Returning False stops the enumeration
return False
# Continue enumerating
return True
def find_window_by_title(title_substring):
global found_hwnd, partial_title
found_hwnd = None
partial_title = title_substring
win32gui.EnumWindows(enum_windows_callback, None)
return found_hwnd
def move_and_resize_window(hwnd, x, y, width, height):
if hwnd is None:
print("No valid window handle provided.")
return False
win32gui.MoveWindow(hwnd, x, y, width, height, True)
return True
if __name__ == "__main__":
# Example usage:
hwnd = find_window_by_title("Cha")
if hwnd:
print(f"Found window with HWND: {hwnd}")
success = move_and_resize_window(hwnd, 100, 100, 800, 600)
if success:
print("Window moved and resized successfully.")
else:
print("Failed to move and resize the window.")
else:
print("No window found containing 'Notepad' in its title.")
运行上面的代码时,有时会出现错误:
pywintypes.error: (126, 'EnumWindows', '找不到指定的模块。')
当我尝试按标题查找已知窗口时会发生这种情况。奇怪的是,如果我查找不存在的标题,它会干净地退出并显示“未找到窗口”。但对于某些现有的窗口,它会抛出错误。
使用 pywin32 时,什么可能导致 EnumWindows 间歇性地抛出“找不到指定的模块”(错误 126)?是否有关于环境、回调的结构方式或我缺少的 pywin32 设置的信息?
任何见解或故障排除步骤将不胜感激。
我尝试过的:
这应该通过 [GitHub] 解决:mhammond/pywin32 - 某些模块错误设置了最后一个错误(计划在下一个版本(v309))。
检查[SO]:如何使用 python 和 win32print 更改打印队列中作业的用户名(@CristiFati 的答案)(最后)以了解进一步的可能方法。