Simulate keypress in a Linux C console application

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.


Solution 1:

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.

Solution 2:

There's a programmable library called 'xdotool':

sudo apt-get install libxdo-dev libxdo2

cat test.c

#include <stdio.h>
#include <stdlib.h>
#include <xdo.h>
#include <unistd.h>
int main() {
    xdo_t * x = xdo_new(":0.0");

    while(1) {
        printf("simulating Shift_L keypress\n");
        xdo_keysequence(x, CURRENTWINDOW, "Shift_L", 0);
        sleep(5);
    }

        return 0; 
}

Run like this:

gcc test.c -lxdo -o test