views:

1846

answers:

1

Is there any way to simulate a keypress in Linux using C?

In my specific situation, I'm on Ubuntu 9.04 and need a simple app that invokes a press on the "pause" button when launched. That would get an iframe in Firefox to refresh using Javascript.

+6  A: 

I assume you mean the "X11 application" - it is not entirely clear from your description what you are planning to do. The below code snippet will send the "pause" keycode to the application that currently has the keyboard input focus under X11 using XTest extension - from what I've read this is the most compatible way to "fake" the keyboard events. See if you might apply this to your scenario (no error check on whether the XOpenDisplay succeeded, to make it simpler).

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
...
Display *display;
unsigned int keycode;
display = XOpenDisplay(NULL);
...
keycode = XKeysymToKeycode(display, XK_Pause);
XTestFakeKeyEvent(display, keycode, True, 0);
XTestFakeKeyEvent(display, keycode, False, 0);
XFlush(display);

You will need to link with the -lX11 -lXtst.

Obviously the firefox would need to have focus at that time.

However, I would be curious to know what is the bigger task that you are trying to accomplish - I suspect there should be a more elegant solution than spoofing the keypress events.

Andrew Y
side comment about my own use case for the above code: I had it an OpenCV-powered weekend hack that allowed me to fake the arrow keypresses by moving my head in front of webcam (so I could scroll the /. posts and eat sandwich at the same time :-)
Andrew Y
I want to use a griffin powermate to reload an iframe :)
Baversjo
Ah, so it's pretty much the same usage as my case :)
Andrew Y