python windows鼠标钩崩溃

时间:2016-07-24 22:56:34

标签: python windows hook mouse

我在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之前,一切似乎都正常工作。一旦我模拟了点击,就会发生崩溃。可能是什么原因?

感谢。

1 个答案:

答案 0 :(得分:1)

看起来def low_level_handler超出范围并被垃圾收集(?)/从内存中删除。在我把它移出def def之后,它全部都在工作。