al sending fake keyboard events, whitespace issues

329 views Asked by At

I'm creating a program using gtk and xlib(xtst) to send fake keypresses to an application, I have created this loop to send the keypresses to the active window:

Display *dis;
        dis = XOpenDisplay(NULL);
        KeyCode modcode = 0; //init value
        int i;
        char hello[]="hello world";
        char temp[1];
        int size=sizeof(hello);
        sleep(2);
        for (i=0;i<size;i++)
        {
                temp[0]=hello[i];
                temp[1]='\0';     //string terminator
                g_print("%s\n",temp);  //works fine, whitespace is printed
                modcode = XKeysymToKeycode(dis, XStringToKeysym(temp));
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
        //      sleep(1);
                XTestFakeKeyEvent(dis, modcode, True, 0);
                XFlush(dis);
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
}

problem is it prints 'helloworld' instead, it is incapable of dealing with whitespace or any special characters

thanks

2

There are 2 answers

0
Adel Ahmed On BEST ANSWER

I just created my own translation function as you had suggested:

switch (hello[i])
{
case ' ':
XTestFakeKeyEvent(dis, 65, True, 0);
XTestFakeKeyEvent(dis, 65, False, 0);

as for capital letters, I used a shift key with the regular key:

case 'T':
XTestFakeKeyEvent(dis, 50, True, 0);
XTestFakeKeyEvent(dis, 28, True, 0);
XTestFakeKeyEvent(dis, 28, False, 0);
XTestFakeKeyEvent(dis, 50, False, 0);
break;

and special characters:

case '\n':
XTestFakeKeyEvent(dis, 36, True, 0);
XTestFakeKeyEvent(dis, 36, False, 0);
break;

things are working fine now, thanks Ishay

12
Ishay Peled On
Display *dis;
        dis = XOpenDisplay(NULL);
        KeyCode modcode = 0; //init value
        int i;
        char hello[]="hello world";
        char temp[2]; //Size is 2!!!
        int size=sizeof(hello);
        sleep(2);
        for (i=0;i<size;i++)
        {
                temp[0]=hello[i];
                temp[1]='\0';     //string terminator
                g_print("%s\n",temp);  //works fine, whitespace is printed
                if (temp[0] == ' ')
                    modcode = XK_KP_Space
                else
                    modcode = XKeysymToKeycode(dis, XStringToKeysym(temp));
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
        //      sleep(1);
                XTestFakeKeyEvent(dis, modcode, True, 0);
                XFlush(dis);
                XTestFakeKeyEvent(dis, modcode, False, 0);
                XFlush(dis);
}

You're storing 2 values into a single value array. Change temp[1] to temp[2] (as in the example).