Vizible’s Blog

Linux – How to simulate key press

Posted in Uncategorized by wearetherock on August 15, 2009

C code from http://stackoverflow.com/questions/1262310/simulate-keypress-linux-c-console-application

// test.c
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>

int main(){
 Display *display;
 unsigned int keycode;
 display = XOpenDisplay(NULL);
 keycode = XKeysymToKeycode(display, XK_A);
 XTestFakeKeyEvent(display, keycode, True, 0);
 keycode = XKeysymToKeycode(display, XK_B);
 XTestFakeKeyEvent(display, keycode, True, 0);
 keycode = XKeysymToKeycode(display, XK_C);
 XTestFakeKeyEvent(display, keycode, True, 0);
 keycode = XKeysymToKeycode(display, XK_D);
 XTestFakeKeyEvent(display, keycode, True, 0);
 XTestFakeKeyEvent(display, keycode, False, 0);
 XFlush(display);
}

Compile

# gcc -lX11 -lXtst test.c

Output

# ./a.out
# abcd
~
Advertisements
Tagged with: , , ,

3 Responses

Subscribe to comments with RSS.

  1. wearetherock said, on August 15, 2009 at 5:41 pm

    if error: X11/extensions/XInput.h: No such file or directory

    try

    sudo apt-get install libxtst-dev 
  2. wearetherock said, on September 11, 2009 at 4:15 am

    Hey, you have to add

    XTestFakeKeyEvent(display, keycode, True, 0);
    XTestFakeKeyEvent(display, keycode, False, 0);
    

    to prevent repeating

  3. jo said, on April 30, 2012 at 12:41 pm

    You shouldn’t use XTest for that:
    “This extension is not intended to support general journaling and playback of user actions.”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: