John Ao
John Ao

Reputation: 159

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?

Upvotes: 1

Views: 1850

Answers (2)

John Ao
John Ao

Reputation: 159

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)

Upvotes: 2

Matthew Connelly
Matthew Connelly

Reputation: 31

SDL2 is a great library for interfacing with hardware and there's a good chance it comes installed with your distro.

This tutorial talks about working with mouse state and I've used it for learning SDL2 overall.

SDL2 documentation is pretty good also: https://wiki.libsdl.org/SDL_GetMouseState

Upvotes: 0

Related Questions