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
");
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
", 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.
");
return -1;
}
printf("Mouse is at (%d,%d)
", root_x, root_y);
free(root_windows);
XCloseDisplay(display);
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…