How can I get the current mouse (pointer) position co-ordinates in X

时光总嘲笑我的痴心妄想 提交于 2019-11-27 14:57:01

问题


This can either be some sample C code or a utility that will show me either gui or on the console it doesn't matter, but I have to be able to "command" it to grab the co-ordinates at an exact time which makes xev not very useful (that I could figure out).


回答1:


I'm not a C programmer by any means but I looked at a couple of online tutorials and think this is how you are supposed to read the current mouse position. This is my own code and I'd done nothing with Xlib before so it could be completely broken (for example, the error handler shouldn't just do nothing for every error) but it works. So here is another solution:

#include <X11/Xlib.h>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <malloc.h>

static int _XlibErrorHandler(Display *display, XErrorEvent *event) {
    fprintf(stderr, "An error occured detecting the mouse position\n");
    return True;
}

int main(void) {
    int number_of_screens;
    int i;
    Bool result;
    Window *root_windows;
    Window window_returned;
    int root_x, root_y;
    int win_x, win_y;
    unsigned int mask_return;

    Display *display = XOpenDisplay(NULL);
    assert(display);
    XSetErrorHandler(_XlibErrorHandler);
    number_of_screens = XScreenCount(display);
    fprintf(stderr, "There are %d screens available in this X session\n", number_of_screens);
    root_windows = malloc(sizeof(Window) * number_of_screens);
    for (i = 0; i < number_of_screens; i++) {
        root_windows[i] = XRootWindow(display, i);
    }
    for (i = 0; i < number_of_screens; i++) {
        result = XQueryPointer(display, root_windows[i], &window_returned,
                &window_returned, &root_x, &root_y, &win_x, &win_y,
                &mask_return);
        if (result == True) {
            break;
        }
    }
    if (result != True) {
        fprintf(stderr, "No mouse found.\n");
        return -1;
    }
    printf("Mouse is at (%d,%d)\n", root_x, root_y);

    free(root_windows);
    XCloseDisplay(display);
    return 0;
}



回答2:


xdotool might be the best tool for this.

For C, you can use libxdo.




回答3:


Actually, xev is very useful if you supply it with the window id grabbed using xwininfo, then it can easily perform this task for you. There are no doubt much more elegant solutions but it works.




回答4:


There's an error on this line

root_windows = malloc(sizeof(Window) * number_of_screens);

Change that to this:

root_windows = (Window *)malloc(sizeof(Window) * number_of_screens);


来源:https://stackoverflow.com/questions/3585871/how-can-i-get-the-current-mouse-pointer-position-co-ordinates-in-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!