获取每个窗口的HWND?

发布于 2021-01-29 19:34:16

我正在开发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
关注者
0
被浏览
83
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    你混了ctypeswin32gui
    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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看