如何在python中使用winapi SetWinEventHook? [英] How to use winapi SetWinEventHook in python?

查看:33
本文介绍了如何在python中使用winapi SetWinEventHook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取从特定应用程序弹出的每个新对话框的句柄.
我知道我应该用 SetWinEventHook 在 Windows 中的 user32.dll 中,但我不知道如何在 python 中做到这一点.你能给我举个例子吗?

I want to get the handle of every new Dialog which pops up from a specific application.
I understand I should set a hook with SetWinEventHook which is in user32.dll in windows, but I don't know how to do that in python. Would you give me an example ?

推荐答案

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

Here's a very simple example that prints to the console the window text for each dialog that is opened:

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中使用winapi SetWinEventHook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆