Python 3.x Python ctypes EnumThreadWindows失败,出现错误87(错误\u无效\u参数)

Python 3.x Python ctypes EnumThreadWindows失败,出现错误87(错误\u无效\u参数),python-3.x,windows,winapi,ctypes,Python 3.x,Windows,Winapi,Ctypes,我似乎无法让窗户工作。它不断失败,出现错误87。代码: error = ctypes.WinDLL('Kernel32').GetLastError enum_func = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) def callback(hwnd, lParam): le

我似乎无法让窗户工作。它不断失败,出现错误87。代码:

error = ctypes.WinDLL('Kernel32').GetLastError
enum_func = ctypes.WINFUNCTYPE(wintypes.BOOL,
                               wintypes.HWND,
                               wintypes.LPARAM)

def callback(hwnd, lParam):
    length = ctypes.WinDLL('User32').GetWindowTextLengthW(hwnd) + 1
    buf = ctypes.create_unicode_buffer(length)
    ctypes.WinDLL('User32').GetWindowTextW(hwnd, buf, length)
    print(buf.value)

worker = enum_func(callback)
test = ctypes.WinDLL('User32').EnumThreadWindows(6000, worker, None)
print(error(test))
我尝试了
pid=wintypes.DWORD(6000)
test=ctypes.windell('User32')。EnumThreadWindows(pid.value,worker,None)
,但没有成功。
我做错了什么?

以下是工作代码。确保传递一个有效的线程ID

您可能会感兴趣的是,LPRAM可以是任何东西,包括python对象,因此,如果传递python对象,则可以在回调中对其进行操作:

导入ctypes
从ctypes导入wintypes
从集合导入namedtuple
Window=namedtuple('Window','hwnd title'))
WNDENUMPROC=ctypes.WINFUNCTYPE(wintypes.BOOL,
wintypes.HWND,
py#允许任何Python对象。
u32=ctypes.windell('user32',使用_last_error=True)#以确保捕获GetLastError
#声明参数和返回类型有助于捕获错误并支持64位。
#HWND在64位Python上是64位的,如果保留ctypes默认值,可能会被截断
#c_int的值(32位)。这段代码适用于Python2.7和3.9。
u32.GetWindowTextLengthW.argtypes=wintypes.HWND,
u32.GetWindowTextLengthW.restype=ctypes.c_int
u32.GetWindowTextW.argtypes=wintypes.HWND,wintypes.LPWSTR,ctypes.c_int
u32.GetWindowTextW.restype=ctypes.c\u int
u32.EnumThreadWindows.argtypes=wintypes.DWORD、WNDENUMPROC、ctypes.py#u object#传递Python对象
u32.EnumThreadWindows.restype=wintypes.BOOL
@WNDENUMPROC#decorator使其成为与ctypes兼容的函数
def回调(hwnd、LPRAM):
长度=u32.GetWindowTextLengthW(hwnd)+1
buf=ctypes。创建\u unicode\u缓冲区(长度)
u32.GetWindowTextW(hwnd、buf、长度)
lParam.append(窗口(hwnd,buf.value))#将数据附加到回调参数
return True#return True继续枚举
结果=[]#一个python对象
如果u32.EnumThreadWindows(6332,回调,结果):#6332是我的explore.exe中的线程
对于wnd in结果:#枚举完成时列出结果
打印(wnd)
其他:
打印('error:',ctypes.get_last_error())#枚举线程窗口的打印错误。
#Python可以使用一个Win32函数,该函数在
#在ctypes调用和调用GetLastError之间
#直接的。
输出:

窗口(hwnd=65832,title='')
窗口(hwnd=65838,标题=“”)
窗口(hwnd=131174,标题=“”)
窗口(hwnd=65682,标题=“”)
窗口(hwnd=65678,标题=“”)
窗口(hwnd=65826,title='Program Manager')
窗口(hwnd=196928,title='MSCTFIME UI')
窗口(hwnd=65680,title='Default-IME')

pid.value
,看起来您传递的是进程id而不是线程id。哦,哈哈。哎呀。谢谢,@Drake Wu。谢谢你的回复和密码,@Mark Tolonen。我有很多东西要学(对编码来说是个新手)。你是怎么得到线程ID的?@Malon