如何在Linux中侦听鼠标事件? [英] How to listen for mouse events in Linux?
本文介绍了如何在Linux中侦听鼠标事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个程序,该程序将在后台运行,并在发生鼠标单击时记录指针的位置.我试图在Google中搜索它,但结果是针对NCurses和一些GUI库的.有什么办法可以编写一个在后台侦听鼠标事件的程序?首选C和/或Python方式.
I want to write a program that would run in the background and log pointer's position when a mouse click occured. I tried to search for it in Google, but results were for NCurses and some GUI libraries. Is there any way that I could write a program that listens to mouse events in the background? C and/or Python ways are prefered.
推荐答案
以下是记录鼠标位置,点击和释放的示例:
Here is an example for logging mouse position, clicks and releases:
#include <stdio.h>
#include <X11/Xlib.h>
char *key_name[] = {
"first",
"second (or middle)",
"third",
"fourth", // :D
"fivth" // :|
};
int main(int argc, char **argv)
{
Display *display;
XEvent xevent;
Window window;
if( (display = XOpenDisplay(NULL)) == NULL )
return -1;
window = DefaultRootWindow(display);
XAllowEvents(display, AsyncBoth, CurrentTime);
XGrabPointer(display,
window,
1,
PointerMotionMask | ButtonPressMask | ButtonReleaseMask ,
GrabModeAsync,
GrabModeAsync,
None,
None,
CurrentTime);
while(1) {
XNextEvent(display, &xevent);
switch (xevent.type) {
case MotionNotify:
printf("Mouse move : [%d, %d]\n", xevent.xmotion.x_root, xevent.xmotion.y_root);
break;
case ButtonPress:
printf("Button pressed : %s\n", key_name[xevent.xbutton.button - 1]);
break;
case ButtonRelease:
printf("Button released : %s\n", key_name[xevent.xbutton.button - 1]);
break;
}
}
return 0;
}
使用以下命令进行编译:
Compile it using:
$ gcc -lX11 mouse.c -o mouse
$ ./mouse
Mouse move : [664, 395]
Mouse move : [665, 393]
Mouse move : [666, 393]
Mouse move : [666, 392]
Mouse move : [664, 392]
Mouse move : [664, 393]
Mouse move : [664, 395]
Button pressed : first
Button released : first
Button pressed : third
Button released : third
^C
$
Look also here Keyboard and Pointer Events and there are a lot of information in The Xlib Manual.
这篇关于如何在Linux中侦听鼠标事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文