Wednesday, April 30, 2008

Generating keypresses on Linux

I was trying to simulate keypress events for some javascript based webpage - actually it was typing the whole alphabet - and I came up with the following code, using Xlib:

#include X11/extensions/XTest.h
#define XK_LATIN1
#define XK_XKB_KEYS
#include X11/keysymdef.h
#include X11/Xlib.h
#include stdio.h
#include stdlib.h
#include sys/time.h

//notice that libraries are lacking < > because of html tags
int main(int argc, char **argv)
Display* pDisplay = XOpenDisplay( ":0.0" );

KeySym key[] = { XK_a,XK_b,XK_c,XK_d,XK_e,

system("sleep 4");
int i;
for( i = 0; i < 26; i++ )
XTestFakeKeyEvent ( pDisplay, XKeysymToKeycode( pDisplay, key[i] ),
True, 0 );
XTestFakeKeyEvent ( pDisplay, XKeysymToKeycode( pDisplay, key[i] ),
False, 0 );

if( pDisplay == NULL ) return 1;

return 0;

In order to compile it, just run:

gcc generateKeys.c -lX11 -lXtst

I hope it helps!


Rafael said...

Oi daniel, sou designer de multimidia e estou trabalhando num prototipo para integrar head e finger tracking num programa 3d. Ai achei os escolhidos pro SOC e o seu projeto que tem tudo a ver.
Eu nao sou programador sou da area de design e queria saber se vc pode me dar umas dicas

Daniel Lélis Baggio said...

Olá, Rafael :)
Não costumo trabalhar com flash/design, mas lembro-me de ter encontrado algo sobre isso. Talvez você devesse dar uma olhada em:
Pretendo integrar o meu projeto ao flash, mas isso só deve ficar pronto em uns 3 meses.
Grande abraço!

Anonymous said...

you have a nice site. thanks for sharing this enormous resources. keep it up. anyway, various kinds of ebooks are available here

creativesumant said...

I need write a C/C++ program for create a batch application
that for each characters read from serial port
create a key press event as the character was generate from user action (key press).

How it's possible?

Recently I just came across a good article on "Linux"
Here is its link.