我正在python中设置一个鼠标挂钩,如下所示:
def listen():
global hook_id
def low_level_handler(aCode, wParam, lParam):
if aCode != win32con.HC_ACTION:
return ctypes.windll.user32.CallNextHookEx(hook_id, aCode, wParam, lParam)
return ctypes.windll.user32.CallNextHookEx(hook_id, aCode, wParam, lParam)
# Our low level handler signature.
CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p))
# Convert the Python handler into C pointer.
pointer = CMPFUNC(low_level_handler)
# Hook both key up and key down events for common keys (non-system).
hook_id = ctypes.windll.user32.SetWindowsHookExA(win32con.WH_MOUSE_LL, pointer,
GetModuleHandle(None), 0)
# Register to remove the hook when the interpreter exits. Unfortunately a
# try/finally block doesn't seem to work here.
atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, hook_id)
def process_msg():
while True:
status, msg = PeekMessage(None, 0, 0, win32con.PM_REMOVE)
if status == 0:
break
TranslateMessage(ctypes.byref(msg))
DispatchMessage(ctypes.byref(msg))
process_msg随后在循环中被调用
一切似乎都很好,直到我在同一个应用程序中模拟鼠标点击的SendInput。一旦我模拟点击,就会崩溃。原因可能是什么?
谢谢。
看起来def low_level_handler超出了范围,正在从内存中进行垃圾收集(?)/删除。在我把它移出def后,听着,一切都正常了。