如何使用Python检测鼠标侧按钮

时间:2012-09-14 16:18:55

标签: python pyhook

我一直在使用pyhook和点击事件的message属性,但似乎只能检测到三个标准按钮。 其他人甚至都没有去找处理程序。

有没有办法检测鼠标可能有的额外按钮?

1 个答案:

答案 0 :(得分:2)

WH_MOUSE_LL挂钩XButtons并且PyHook的dll将它传递给python,但是python端的HookManager忽略它们。但是,您可以跳过HookManager并直接使用cpyHook接口。

此示例在按下按钮时将xbutton事件打印到控制台,并在按下鼠标左键时退出:

from pyHook import cpyHook, HookConstants
import pythoncom
import ctypes
user32 = ctypes.windll.user32

XBUTTON1 = 0x0001
XBUTTON2 = 0x0002

wm = { 0x020B: "WM_XBUTTONDOWN", 0x020C: "WM_XBUTTONUP", 0x0201: "WM_LBUTTONDOWN", }

def mouse_handler(msg, x, y, data, flags, time, hwnd, window_name):
    name = wm.get(msg, None)
    if name:
        xb = data >> 16  # high word indicates which xbutton
        print(name, xb & XBUTTON1, xb & XBUTTON2)
        if name == "WM_LBUTTONDOWN":
            user32.PostQuitMessage(0)
    return True  # True = pass the event to other handlers

try:
    cpyHook.cSetHook(HookConstants.WH_MOUSE_LL, mouse_handler)
    pythoncom.PumpMessages() # returns on WM_QUIT
finally:
    cpyHook.cUnhook(HookConstants.WH_MOUSE_LL)