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_MISCELLANY
#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,
XK_f,XK_g,XK_h,XK_i,XK_j,
XK_k,XK_l,XK_m,XK_n,XK_o,
XK_p,XK_q,XK_r,XK_s,XK_t,
XK_u,XK_v,XK_w,XK_x,XK_y,
XK_z};

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;

XCloseDisplay(pDisplay);
return 0;
}

In order to compile it, just run:


gcc generateKeys.c -lX11 -lXtst


I hope it helps!

4 comments:

Anonymous 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
obrigado
Rafael

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:
http://www.nastypixel.com/prototype/project/flash-motion-tracking/
ou
http://www.youtube.com/watch?v=tvVyDmTCNwE
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

http://feboook.blogspot.com

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.