在没有 X Window 的情况下用 C 语言在 GNU/Linux 中捕获击键 [英] Capturing keystrokes in GNU/Linux in C without X Window

查看:51
本文介绍了在没有 X Window 的情况下用 C 语言在 GNU/Linux 中捕获击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在应用程序中工作,并且从键盘上按了一个键,那么如何在C语言中,在GNU/LINUX下,在C语言下,没有用户使用X Window的情况下捕获该键(或字符串),包括源应用程序的名称?

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?

推荐答案

如果没有X Window,此问题将更加困难.

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

对于按键部分,您可以使用与此代码相似的代码,但必须将设备作为要读取的参数传递(键盘,通常为/dev/input/event0 )

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);

        }
    }

信用不归我所有.该代码来自Ventriloctrl黑客,以获取击键- http://public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz .

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.

这篇关于在没有 X Window 的情况下用 C 语言在 GNU/Linux 中捕获击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆