Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending fake keypress event to a window using xlib

Tags:

c

linux

xlib

I'm trying to use C and xlib to send a fake keypress event to the window with focus, here's my code:

#include <X11/Xlib.h>
#include <X11/keysymdef.h>
#define XK_A            0x041

int main()
{
        Display *display = XOpenDisplay(NULL);
        //find out window with current focus:
        Window winfocus;
        int    revert;
        XGetInputFocus(display, &winfocus, &revert);

        //send key event to taht window
        KeySym sym;
        sym=XStringToKeysym("a");
        //event definition
        XKeyEvent event;
        event.type=KeyPress;
        event.keycode=XK_A;
        event.display=display;
        event.root=winfocus;
        XSendEvent(display,winfocus,True,KeyPressMask,(XEvent *)&event);

        return 0;
}

I'm trying to keep the code as simple as possible, I want to send the letter A to the active window I think I'm doing something wrong though

thanks


I tried the following code:

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>
#include <unistd.h>


int main()
{
        Display *dis;
        dis = XOpenDisplay(NULL);
        KeyCode modcode = 0; //init value
        modcode = XKeysymToKeycode(dis, XK_B);
        XTestFakeKeyEvent(dis, modcode, True, 0);
        XFlush(dis);
        sleep(1);
        XTestFakeKeyEvent(dis, modcode, False, 0);
        XFlush(dis);
        modcode = XKeysymToKeycode(dis, XK_A);
        XTestFakeKeyEvent(dis, modcode, True, 0);
        XFlush(dis);




        return 0;
}

which presses the a key repeatedly, I'm unable to release that button if I dont use the sleep function, I'm unable to type the letter in once and then release the key press

like image 947
Adel Ahmed Avatar asked May 23 '15 13:05

Adel Ahmed


1 Answers

I got it. I am not sure if this is the right way to do it, but it gets the job done. A key release before the keypress fixed everything.

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>


int main() {
        Display *dis;
        dis = XOpenDisplay(NULL);
        KeyCode modcode = 0; //init value
        int i;
        for (i=0;i<5;i++) {
                modcode = XKeysymToKeycode(dis, XStringToKeysym("a"));
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
                sleep(1);
                XTestFakeKeyEvent(dis, modcode, True, 0);
                XFlush(dis);
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
        }
        return 0;
}

This will type in 5 'a's.

like image 150
Adel Ahmed Avatar answered Nov 02 '22 09:11

Adel Ahmed