我在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 listen之后,这一切都奏效了。