获取每个窗口的HWND?
我正在开发python应用程序,我想获取HWND
每个打开的窗口。我需要窗口的名称和HWND
来过滤列表,以管理一些特定的窗口,移动它们并调整其大小。
我试图自己查看信息,但没有获得正确的代码。我尝试使用此代码,但仅获得每个窗口的标题(很棒),但我也需要HWND
。
import ctypes
import win32gui
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
titles = []
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
GetWindowText(hwnd, buff, length + 1)
titles.append((hwnd, buff.value))
return True
EnumWindows(EnumWindowsProc(foreach_window), 0)
for i in range(len(titles)):
print(titles)[i]
win32gui.MoveWindow((titles)[5][0], 0, 0, 760, 500, True)
这里有一个错误:
win32gui.MoveWindow((titles)[5][0], 0, 0, 760, 500, True)
TypeError: The object is not a PyHANDLE object
-
你混了
ctypes
和win32gui
。
在hwnd
你所得到的是通过获得ctypes
,是一个LP_c_long
对象。这就是为什么win32gui.MoveWindow
不接受它。你应该把它传给ctypes.windll.user32.MoveWindow(titles[5][0], 0, 0, 760, 500, True)
如果要使用
win32gui.MoveWindow
,则可以直接使用python函数作为回调。
例如,import win32gui def enumHandler(hwnd, lParam): if win32gui.IsWindowVisible(hwnd): if 'Stack Overflow' in win32gui.GetWindowText(hwnd): win32gui.MoveWindow(hwnd, 0, 0, 760, 500, True) win32gui.EnumWindows(enumHandler, None)