Skip to content

Instantly share code, notes, and snippets.

@brccabral
Created March 20, 2024 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brccabral/33ae32ed8275743099bba732f45e8ced to your computer and use it in GitHub Desktop.
Save brccabral/33ae32ed8275743099bba732f45e8ced to your computer and use it in GitHub Desktop.
XGrabKey
// Original from https://gist.github.com/jouyouyun/669726de58df8d333666
// Compile: gcc xgrabkey.c `pkg-config --cflags --libs x11` -o xgrabkey
#include <stdio.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main()
{
Window root;
Display *dpy = NULL;
dpy = XOpenDisplay(0);
if (dpy == NULL)
{
printf("Open Display Failed\n");
return -1;
}
root = DefaultRootWindow(dpy);
// unsigned int mod = AnyModifier; // grabs any modifier, or none, will grab Ctrl+C
unsigned int mods[] = {0, ShiftMask, Mod1Mask, ShiftMask | Mod1Mask};
// 0 - grabs just the key
// ShiftMask - grabs if Shift is pressed
// Mod1Mask - grabs if Alt is pressed
// ShiftMask | Mod1Mask - grabs if Shift and Alt are pressed
for (char k = 'a'; k <= 'z'; ++k)
{
char key[] = {k, '\0'};
int sym = XStringToKeysym(key);
int code = XKeysymToKeycode(dpy, sym);
for (unsigned int m = 0; m < sizeof(mods) / sizeof(mods[0]); ++m)
{
unsigned int mod = mods[m];
XGrabKey(dpy, code, mod, root, True, GrabModeAsync, GrabModeAsync);
}
printf("sym %d code %d\n", sym, code);
}
XEvent event;
for (;;)
{
XNextEvent(dpy, &event);
unsigned int code = event.xkey.keycode;
KeySym sym = XKeycodeToKeysym(dpy, event.xkey.keycode, 0);
char *key = XKeysymToString(sym);
printf("Key event code %u symbol %lu key %s\n",
code,
sym,
key);
if (event.type == KeyPress)
{
printf("Key press\n");
}
if (event.type == KeyRelease)
{
printf("Key release\n");
}
if (sym == XStringToKeysym("z"))
break;
}
XAllowEvents(dpy, AsyncKeyboard, CurrentTime);
XUngrabKey(dpy, AnyKey, AnyModifier, root);
XSync(dpy, False);
XCloseDisplay(dpy);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment