Simulate keypress in a Linux C console application

21,033

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

Share:
21,033
Baversjo
Author by

Baversjo

Student studying programming

Updated on July 16, 2022

Comments

  • Baversjo
    Baversjo almost 2 years

    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.

  • Andrew Y
    Andrew Y over 14 years
    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 :-)
  • Baversjo
    Baversjo over 14 years
    I want to use a griffin powermate to reload an iframe :)
  • Andrew Y
    Andrew Y over 14 years
    Ah, so it's pretty much the same usage as my case :)
  • Shambhav Gautam
    Shambhav Gautam almost 3 years
    Do you have the link for the documentation? I can't find anything for the programmatical part of xdotool.