2

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?

Fábio Diniz
  • 10,077
  • 3
  • 38
  • 45

2 Answers2

3

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)
Kevin Edwards
  • 360
  • 1
  • 3
  • 6
2

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.

Community
  • 1
  • 1
l4mpi
  • 5,103
  • 3
  • 34
  • 54