简体   繁体   English

linux中如何捕捉和修改鼠标事件?

[英]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.但是我对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?如何使用 C++/Python 做到这一点? What tools or libraries should I use?我应该使用哪些工具或库?

SDL2 is a great library for interfacing with hardware and there's a good chance it comes installed with your distro. SDL2 是一个很好的与硬件接口的库,它很有可能随您的发行版一起安装。

This tutorial talks about working with mouse state and I've used it for learning SDL2 overall. 本教程讨论了如何使用鼠标 state,我用它来学习 SDL2。

SDL2 documentation is pretty good also: https://wiki.libsdl.org/SDL_GetMouseState SDL2 文档也很不错: https://wiki.libsdl.org/SDL_GetMouseState

My problem was solved using python-evdev使用python-evdev解决了我的问题

Turns out it's quite simple.事实证明这很简单。 Just grab mouse and create another uinput to write desired event.只需抓住鼠标并创建另一个 uinput 来编写所需的事件。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM