如何使用 ctypes.windll.user32.SetWindowsHookExW 挂钩 ctypes.windll.user32.MessageBoxW?

问题描述 投票:0回答:1

我想制作一个笑话程序,首先它打开一个消息框,关闭后另一个消息框出现在随机位置。它会一直这样重复,直到有什么东西终止了它的任务。使用 tkinter 消息框,那么这些消息框就无法被挂钩,我必须制作另一个 tkinter 表单(这真的很难看,并且与 Windows 消息框不同)。所以我切换到 ctypes,问题就开始了。然后,我为钩子创建了一个回调函数,当我将该函数传递给 ctypes.windll.user32.SetWindowsHookExA 函数的第二个参数时,它显示 TypeError: 错误类型。我该如何解决这个问题?

我尝试将函数转换为 c_void_p,但这样做只会得到更多错误,例如“非法指令”。

这是我的代码:

import ctypes, random

def msgBoxHook(nCode, wParam, lParam):
 if nCode == 3:
  hwnd = ctypes.wintypes.HWND
  hwnd = wParam

  msgRekt = ctypes.wintypes.RECT # >:)

  ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(msgRekt))
  ctypes.windll.user32.MoveWindow(hwnd, randint(0, ctypes.windll.user32.GetSystemMetrics(0)), randint(0, ctypes.windll.user32.GetSystemMetrics(1)), msgRekt.right - msgRekt.left, msgRekt.bottom - msgRekt.top, True)
 return ctypes.windll.user32.CallNextHookEx(0, nCode, wParam, lParam)

# When I try to call
ctypes.windll.user32.SetWindowsHookExA(5, msgBoxHook, 0, ctypes.windll.kernel32.GetCurrentThreadId())

# It shows:
"""
Traceback (most recent call last):
  File "test.py", line 1, in <module>
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
"""

预期:当使用 ctypes.windll.user32.MessageBoxW(None, 'Hello', 'World', 0x00000010 | 0x00000000) 时,它会在随机位置打开一个消息框,标题为“World”,文本为“Hello”,停止图标为 OK按钮。

现实:如上图。

python ctypes
1个回答
0
投票

清单 [Python.Docs]:ctypes - Python 的外部函数库

你不能将 Python 对象传递给普通 C 函数(我的意思是你可以,但结果不会是预期的)。

[MS.Learn]:SetWindowsHookExA 函数 (winuser.h) 需要一个 [MS.Learn]:CBTProc 回调函数,当其 1st 参数为 WH_CBT (5) 时。
所以,你必须包装你的函数:

import ctypes as cts
from ctypes import wintypes as wts


WH_CBT = 5

HOOKProc = cts.WINFUNCTYPE(wts.LPVOID, cts.c_int, wts.WPARAM, wts.LPARAM)
CBTProc = HOOKProc

hook = cts.windll.user32.SetWindowsHookExA(WH_CBT, CBTProc(msgBoxHook), 0, cts.windll.kernel32.GetCurrentThreadId())

这应该可以帮助您解决当前的问题。但你肯定会遇到其他人(当然这可能是其他问题的主题)。

我已经发现,您没有为您使用的任何函数定义 ArgTypesResType
检查 [SO]:通过 ctypes 从 Python 调用的 C 函数返回不正确的值(@CristiFati 的答案),了解有关该主题的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.