Reputation: 176
I'm setting up a mouse hook in python like that:
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 is then later called in a loop
Everything seems to be working fine until I do SendInput that simulates a mouse click from within the same app. Once I simulate click, there's a crash. What could possibly be the cause?
Thanks.
Upvotes: 1
Views: 592
Reputation: 176
It looks like def low_level_handler was going out of scope and being garbage collected (?) / removed from memory. After I moved it out of def listen, it's all working.
Upvotes: 1