Skip to content

Instantly share code, notes, and snippets.

@javiercantero
Last active June 24, 2024 16:45
Show Gist options
  • Save javiercantero/7753445 to your computer and use it in GitHub Desktop.
Save javiercantero/7753445 to your computer and use it in GitHub Desktop.
A X11/Xlib program that reads the KeyPress and KeyRelease events from the window and prints them to the standard output. Used to debug the keyboard within X.
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
Display *display;
Window window;
XEvent event;
int s;
/* open connection with the server */
display = XOpenDisplay(NULL);
if (display == NULL)
{
fprintf(stderr, "Cannot open display\n");
exit(1);
}
s = DefaultScreen(display);
/* create window */
window = XCreateSimpleWindow(display, RootWindow(display, s), 10, 10, 200, 200, 1,
BlackPixel(display, s), WhitePixel(display, s));
/* select kind of events we are interested in */
XSelectInput(display, window, KeyPressMask | KeyReleaseMask );
/* map (show) the window */
XMapWindow(display, window);
/* event loop */
while (1)
{
XNextEvent(display, &event);
/* keyboard events */
if (event.type == KeyPress)
{
printf( "KeyPress: %x\n", event.xkey.keycode );
/* exit on ESC key press */
if ( event.xkey.keycode == 0x09 )
break;
}
else if (event.type == KeyRelease)
{
printf( "KeyRelease: %x\n", event.xkey.keycode );
}
}
/* close connection to server */
XCloseDisplay(display);
return 0;
}
@jtayl711
Copy link

I'm trying to detect the moment a key is pressed and the moment a key is released. Using your program I'm getting a "KeyRelease:" message even when I'm holding down a key. Can you help me detect only when a Key is pressed and only when it's released?

@javiercantero
Copy link
Author

I'm afraid you have to filter out the additional KeyPress events (and KeyRelease events if the autorepeat function is enabled).

@frank4dos
Copy link

Hey Javier,

I have a little C text mode application running under Gnome Terminal.

After receiving a keystring through the terminal, it can proceed with its own function associated with it. Let's say it receives "^H".

The string "^H" is produced pressing ctrl-h (two keys) or ctrl-backspace, also two keys. There is no way to change that in the terminal.

I would like to use your little xreadkeys.c to read the keycodes and tell which keys were pressed.

However, how can I change your program and make it use the window already open without creating a new one?

Thanks and regards

frank

@angeldollface
Copy link

@javiercantero How would I intercept a keypress on the root window? (The one that X draws everything on?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment