Created
March 20, 2024 23:40
-
-
Save brccabral/33ae32ed8275743099bba732f45e8ced to your computer and use it in GitHub Desktop.
XGrabKey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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