For learning purposes, I was hoping to write a small C program that would wait for the next Button Press anywhere on the display. After reading through a bunch of the Xlib documentation, I thought this would work:
Code:
#include <X11/Xlib.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
Display * dpy = XOpenDisplay(NULL);
if(dpy == NULL) {
fprintf(stderr, "error: could not open display.");
exit(EXIT_FAILURE);
}
Window rootw = XDefaultRootWindow(dpy);
XSelectInput(dpy, rootw, ButtonPressMask);
XEvent * e;
XNextEvent(dpy, e);
/*
Display some information about the event probably...
*/
}
But that always dies with:
Code:
X Error of failed request: BadAccess (attempt to access private resource denied)
Major opcode of failed request: 2 (X_ChangeWindowAttributes)
Serial number of failed request: 7
Current serial number in output stream: 7
Edit: I think the problem above is that I am not grabbing the pointer first. This seems to work:
Code:
#include <X11/Xlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <X11/cursorfont.h>
int main() {
Display * dpy = XOpenDisplay(NULL);
if(dpy == NULL) {
fprintf(stderr, "error: could not open display.");
exit(EXIT_FAILURE);
}
Cursor csr = XCreateFontCursor(dpy, XC_crosshair);
switch(csr) {
case BadAlloc:
fprintf(stderr, "error: BadAlloc during XCreateFontCursor");
exit(EXIT_FAILURE);
case BadValue:
fprintf(stderr, "error: BadValue during XCreateFontCursor");
exit(EXIT_FAILURE);
}
Window rootw = XDefaultRootWindow(dpy);
XEvent evt;
int err = XGrabPointer(dpy,
rootw,
False,
ButtonPressMask,
GrabModeAsync,
GrabModeAsync,
None,
csr,
CurrentTime);
switch(err) {
case BadCursor:
fprintf(stderr, "error: BadCursor during XGrabPointer");
exit(EXIT_FAILURE);
case BadValue:
fprintf(stderr, "error: BadCursor during XGrabPointer");
exit(EXIT_FAILURE);
case BadWindow:
fprintf(stderr, "error: BadCursor during XGrabPointer");
exit(EXIT_FAILURE);
}
XNextEvent(dpy, &evt);
printf("got it!\n");
/*
Display some information about the event probably...
*/
}
Is there anything technically wrong with this approach?