如果我在一个应用程序中工作并且我按下键盘上的一个键,我如何在没有 X Window 的情况下,在 C 中,在 GNU/LINUX 下,在用户空间中捕获该键(或字符串),包括源应用程序的名称?
最佳答案
好吧,如果没有 X Window,这个问题就更难了。
对于击键部分,您可以使用与此类似的代码,但您必须将设备作为您正在读取的参数传递(键盘,通常是/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 hack 以获取击键 - http://public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz .
关于在没有 X Window 的情况下在 C 中捕获 GNU/Linux 中的击键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1485116/