linux c/c++监听鼠标或键盘事件
1、输入设备在文件/proc/bus/input/devices中,如:
其中Handlers=kbd event2,说明其值可以在/dev/input文件夹的event2文件中读到,文件夹内容:
2、可能是受虚拟机影响,鼠标事件并不能从mousex系列的文件中读到,而是event3,键盘是event2,完整程序如下:
- #include <stdio.h>
- #include <linux/input.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- int main(int argc,char** argv)
- {
- int keys_fd;
- char ret[2];
- struct input_event t;
- keys_fd=open(argv[1],O_RDONLY);
- if(keys_fd<=0)
- {
- printf("error\n");
- return -1;
- }
- while(1)
- {
- read(keys_fd,&t,sizeof(struct input_event));
- if(t.type==1)
- printf("key %i state %i \n",t.code,t.value);
- }
- close(keys_fd);
- return 0;
- }
3、键盘事件效果:
本文介绍如何在Linux环境下使用C/C++语言监听输入设备的鼠标和键盘事件,通过读取/proc/bus/input/devices文件获取设备信息,并通过open()函数打开设备文件进行事件监听。

3707

被折叠的 条评论
为什么被折叠?



