获取每个窗口的 HWND? [英] Get HWND of each Window?
问题描述
我正在开发一个 python 应用程序,我想获取每个打开的窗口的 HWND
.我需要窗口的名称和 HWND
来过滤列表以管理一些特定的窗口,移动和调整它们的大小.
I am developing a python application and I want to get the HWND
of each open windows. I need the name of the windows and the HWND
to filter the list to manage some specifics windows, moving and resizing them.
我曾尝试自己查看周围的信息,但没有得到正确的代码段.我试过这个代码,但我只获取每个窗口的标题(这很好),但我也需要 HWND
.
I have tried to do it myself looking information around but I did not get the correct piece of code. I tried with this code but I only get the title of each windows (that is great), but I need the HWND
too.
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
不接受它的原因.你应该把它传给
You mixed up ctypes
and win32gui
.
The hwnd
you've got is obtained via ctypes
and is a LP_c_long
object. That's why win32gui.MoveWindow
didn't accept it. You should pass it to
ctypes.windll.user32.MoveWindow(titles[5][0], 0, 0, 760, 500, True)
如果你想使用win32gui.MoveWindow
,你可以直接使用python函数作为回调.
例如,
If you want to use win32gui.MoveWindow
, you can use python function as callback directly.
For example,
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)
这篇关于获取每个窗口的 HWND?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!