Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <X11/Xlib.h>
- #include <X11/keysym.h>
- void injectToCurrentWindow(Display* targetDisplay, Window rootWindow, KeySym keyToInject, int keyModifiers, int keyPress)
- {
- Window xFocused;
- XKeyEvent xInputEvent;
- int xRevert;
- XGetInputFocus(targetDisplay, &xFocused, &xRevert);
- xInputEvent.display = targetDisplay;
- xInputEvent.window = xFocused;
- xInputEvent.root = rootWindow;
- xInputEvent.subwindow = None;
- xInputEvent.time = CurrentTime;
- xInputEvent.x = 1;
- xInputEvent.y = 1;
- xInputEvent.x_root = 1;
- xInputEvent.y_root = 1;
- xInputEvent.same_screen = True;
- xInputEvent.keycode = XKeysymToKeycode(targetDisplay, keyToInject);
- xInputEvent.state = keyModifiers;
- /* Take key press or release accordingly and dispatch event */
- xInputEvent.type = keyPress?KeyPress:KeyRelease;
- XSendEvent(xInputEvent.display,xInputEvent.window, True, KeyPressMask, (XEvent*) &xInputEvent );
- }
- int main(void)
- {
- Display* xDisplay;
- Window xRoot;
- KeySym xKeyPressed;
- XEvent xKeyEvent;
- int runLoop = 1;
- /* Just open default display and check for errors */
- xDisplay = XOpenDisplay(0);
- if (!xDisplay){
- fprintf(stderr,"Failed to open display ! \r\n");
- exit(1);
- }
- /* Get root window and do the actual grab ... this will fail of other app has a grab */
- xRoot = DefaultRootWindow(xDisplay);
- XGrabKeyboard(xDisplay, xRoot, False, GrabModeAsync, GrabModeAsync, CurrentTime);
- while(runLoop){
- /* Peek events */
- XNextEvent(xDisplay,&xKeyEvent);
- if (xKeyEvent.type == KeyPress || xKeyEvent.type == KeyRelease){
- /* Convert and operate with KeySym ... We only allow "a" to pass, "q" stops the software */
- xKeyPressed = XKeycodeToKeysym(xDisplay, xKeyEvent.xkey.keycode, 0);
- if (xKeyPressed == XK_a) injectToCurrentWindow(xDisplay, xRoot, XK_a, xKeyEvent.xkey.state, xKeyEvent.type == KeyPress?1:0 );
- if (xKeyPressed == XK_q) runLoop = 0;
- printf("[%s] You shall not pass !!! \r\n",XKeysymToString(xKeyPressed));
- }
- }
- XUngrabKeyboard(xDisplay,CurrentTime);
- XCloseDisplay(xDisplay);
- }
Advertisement
Add Comment
Please, Sign In to add comment