Capturing keystrokes in GNU/Linux in C without X Window

r00t3r picture r00t3r · Sep 28, 2009 · Viewed 24.3k times · Source

If I am working in an application and I press a key from the keyboard, how can I capture that key (or string), including the source application's name, in C, under GNU/LINUX, in userland, without X Window?

Answer

aemus picture aemus · Sep 28, 2009

Well, without X Window this problem is way more difficult.

For the keystroke part, you can use code similar to this one, but you have to pass the device as an argument that you are reading (keyboard, usually /dev/input/event0)

#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int fd;
    if(argc < 2) {
        printf("usage: %s <device>\n", argv[0]);
        return 1;
    }

    fd = open(argv[1], O_RDONLY);
    struct input_event ev;

    while (1)
    {
        read(fd, &ev, sizeof(struct input_event));

        if(ev.type == 1)
            printf("key %i state %i\n", ev.code, ev.value);

        }
    }

Credits do not go to me. This code is taken from the Ventriloctrl hack to get keystrokes - http://public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz.