如何在Linux中监听鼠标事件?

时间:2013-01-27 23:14:35

标签: linux mouseevent x11

我想写一个程序,它会在后台运行并在鼠标点击时记录指针的位置。我试图在谷歌搜索它,但结果是NCurses和一些GUI库。有什么办法可以编写一个在后台监听鼠标事件的程序吗?首选C和/或Python方式。

2 个答案:

答案 0 :(得分:9)

以下是记录鼠标位置,点击和释放的示例:

#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;
}

使用以下方式编译:

$ 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
$

另请参见Keyboard and Pointer EventsThe Xlib Manual中有很多信息。

答案 1 :(得分:0)

类似的问题:How can I capture mouseevents and keyevents using python in background on linux

上面的答案是使用python绑定evdev。此绑定可用于捕获鼠标事件。