How to detect mouse side buttons with Python

房东的猫 提交于 2019-12-23 01:52:44

问题


I've been using pyhook and the message attribute of the clicking events, but it seems to be able to detect just the three standard buttons. The others don't even get to the handler.

Is there a way to detect the extra buttons that the mouse might have?


回答1:


From the documentation for WH_MOUSE_LL:

wParam [in]
Type: WPARAM

The identifier of the mouse message. This parameter can be one of the following messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOUSEHWHEEL, WM_RBUTTONDOWN, or WM_RBUTTONUP.

As pyhook uses the WH_MOUSE_LL hook it seems it is limited to these three buttons.

Following this answer, you could use pywin32 and track the WM_XBUTTONDOWN message which should to my understanding get fired for mouse buttons 4 and 5.




回答2:


WH_MOUSE_LL does hook XButtons and PyHook's dll passes it through to python, but the HookManager on the python side ignores them. However, you can skip HookManager and use the cpyHook interface directly.

This example prints xbutton events to the console as they are pressed and exits when the left mouse button is pressed:

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)


来源:https://stackoverflow.com/questions/12428351/how-to-detect-mouse-side-buttons-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!