C language - trigger key events in Linux with xdo

I needed a C library to build a small app that triggers keyboard events in Linux. Luckily I have found xdotool by Jordan Sissel that also contains the library libxdo.

Install libxdo

The library can be installed easely on Debian based systems with the following command. Requirement are super user permissions.

apt-get install libxdo-dev

xdo hello world example

I want to write a small xdo hello world application that is doing a little bit more with the keyboard as only printing characters.

Procedure

The xdo hello world example should have the following procedure that simulates a human on an text editor.

  • We start our xdo hello world application in the terminal
  • We focus on our favorite text editor
  • The xdo application is writing Hallo xdo! into the editor
  • The xdo application checks that Hallo is wrong and presses eight times the Left button on the keyboard
  • The xdo application removes the a character with the BackSpace button and writes an e character instead

C code

Here is the C programming language code for the procedure above that will be saved to a file xdo-hello.c.

#include <xdo.h>

int main() {
    xdo_t * x = xdo_new(NULL);

    sleep(5);
    xdo_enter_text_window(x, CURRENTWINDOW, "Hallo xdo!", 500000);
    int i;
    for (i = 0; i < 8; i = i + 1) {
        xdo_send_keysequence_window(x, CURRENTWINDOW, "Left", 200000);
    }
    xdo_send_keysequence_window(x, CURRENTWINDOW, "BackSpace+e", 200000);
    xdo_free(x);

    return 0;
}

Compile xdo hello world

We can compile the code from above with the following command.

gcc xdo-hello.c -lxdo -o xdo-hello

Execute xdo hello world

The small xdo hello world application can be executed with the following command. Do not forget to focus on your text editor window after starting the application.

./xdo-hello

The behavior in your text editor should something like this.

Next Previous