Skip to content
Advertisement

How to capture and modify mouse events in linux?

I want to write a program that changes the behavior of mouse when certain key is pressed. But I am not quite familiar with event mechanisms in linux.

My guess is that I need to filter through the “event queue” looking for “key press” and “mouse press” events, and somehow modify the mouse event before passing it on or discard it and create a new one.

How can this be done using C++/Python? What tools or libraries should I use?

Advertisement

Answer

My problem was solved using python-evdev

Turns out it’s quite simple. Just grab mouse and create another uinput to write desired event.

import evdev
from evdev import ecodes

key=ecodes.KEY_LEFTSHIFT
kb=evdev.InputDevice('/dev/input/event1')     # keybord
mouse=evdev.InputDevice('/dev/input/event3')  # mouse
dummy=evdev.UInput.from_device(mouse)
hwheel=evdev.UInput({ecodes.EV_REL:[ecodes.REL_HWHEEL]})
mouse.grab()
for event in mouse.read_loop():
    if event.type==ecodes.EV_REL and event.code==ecodes.REL_WHEEL and key in kb.active_keys():
            hwheel.write(ecodes.EV_REL, ecodes.REL_HWHEEL, event.value)
            hwheel.write(ecodes.EV_SYN, ecodes.SYN_REPORT, 0)
    else:
        dummy.write_event(event)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement