在Python中枚举Windows槽ctypes

gcq*_*gcq 2 python winapi ctypes

我正在尝试使用Python3.3中的ctypes获取所有可见窗口的列表

但是使用我拥有的代码,不会返回单个窗口。该EnumWindows函数失败,并且返回的错误代码为0。

import ctypes

user32 = ctypes.windll.user32

def worker(hwnd, lParam):
    length = user32.GetWindowTextLengthW(hwnd) + 1
    buffer = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hwnd, buffer, length)
    print("Buff: ", repr(buffer.value))

a = ctypes.WINFUNCTYPE(ctypes.c_bool,
                       ctypes.POINTER(ctypes.c_int),
                       ctypes.POINTER(ctypes.c_int))(worker)

if not user32.EnumWindows(a, True):
    print("Err: ", ctypes.windll.kernel32.GetLastError())
Run Code Online (Sandbox Code Playgroud)

这是当前输出:

Buff:  ''
Err:  0
Run Code Online (Sandbox Code Playgroud)

这就是我所期望的:

Buff: 'Python 3.3.2 shell'
Buff: 'test.py - C:\Users\...'
[...]
Run Code Online (Sandbox Code Playgroud)

您能指出我正确的方向吗?提前致谢。

Ery*_*Sun 5

回调需要返回TRUE以继续枚举。您的回调隐式返回None,这是错误的。下面的修订版应该可以满足您的要求:

import ctypes
from ctypes import wintypes

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL,
                                 wintypes.HWND,
                                 wintypes.LPARAM)
user32 = ctypes.windll.user32
user32.EnumWindows.argtypes = [
    WNDENUMPROC,
    wintypes.LPARAM]
user32.GetWindowTextLengthW.argtypes = [
    wintypes.HWND]
user32.GetWindowTextW.argtypes = [
    wintypes.HWND,
    wintypes.LPWSTR,
    ctypes.c_int]

def worker(hwnd, lParam):
    length = user32.GetWindowTextLengthW(hwnd) + 1
    buffer = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hwnd, buffer, length)
    print("Buff: ", repr(buffer.value))
    return True

cb_worker = WNDENUMPROC(worker)
if not user32.EnumWindows(cb_worker, 42):
    raise ctypes.WinError()
Run Code Online (Sandbox Code Playgroud)

HWND手柄类型是一个别名c_void_pLPARAM是一个与指针相同的存储大小的整数。其定义如下wintypes

if ctypes.sizeof(ctypes.c_long) == ctypes.sizeof(ctypes.c_void_p):
    WPARAM = ctypes.c_ulong
    LPARAM = ctypes.c_long
elif ctypes.sizeof(ctypes.c_longlong) == ctypes.sizeof(ctypes.c_void_p):
    WPARAM = ctypes.c_ulonglong
    LPARAM = ctypes.c_longlong
Run Code Online (Sandbox Code Playgroud)