gpt4 book ai didi

python - 如何在 python 中使用 winapi SetWinEventHook?

转载 作者:太空狗 更新时间:2023-10-29 22:27:07 25 4
gpt4 key购买 nike

我想获取从特定应用程序弹出的每个新对话框的句柄。
我知道我应该设置一个钩子(Hook) SetWinEventHook它在 Windows 中的 user32.dll 中,但我不知道如何在 python 中执行此操作。你能举个例子吗?

最佳答案

这是一个非常简单的示例,它向控制台打印每个打开的对话框的窗口文本:

import sys
import time
import ctypes
import ctypes.wintypes

EVENT_SYSTEM_DIALOGSTART = 0x0010
WINEVENT_OUTOFCONTEXT = 0x0000

user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32

ole32.CoInitialize(0)

WinEventProcType = ctypes.WINFUNCTYPE(
None,
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD
)

def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime):
length = user32.GetWindowTextLengthA(hwnd)
buff = ctypes.create_string_buffer(length + 1)
user32.GetWindowTextA(hwnd, buff, length + 1)
print buff.value

WinEventProc = WinEventProcType(callback)

user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
hook = user32.SetWinEventHook(
EVENT_SYSTEM_DIALOGSTART,
EVENT_SYSTEM_DIALOGSTART,
0,
WinEventProc,
0,
0,
WINEVENT_OUTOFCONTEXT
)
if hook == 0:
print 'SetWinEventHook failed'
sys.exit(1)

msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
user32.TranslateMessageW(msg)
user32.DispatchMessageW(msg)

user32.UnhookWinEvent(hook)
ole32.CoUninitialize()

关于python - 如何在 python 中使用 winapi SetWinEventHook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com