http://blog.csdn.net/liang12360640/article/details/50350648

来源:互联网 发布:旅游市场数据 编辑:程序博客网 时间:2024/06/06 01:02

linux c/c++监听鼠标或键盘事件

1、输入设备在文件/proc/bus/input/devices中,如:


其中Handlers=kbd event2,说明其值可以在/dev/input文件夹的event2文件中读到,文件夹内容:



2、可能是受虚拟机影响,鼠标事件并不能从mousex系列的文件中读到,而是event3,键盘是event2,完整程序如下:

[cpp] view plain copy print?
  1. #include <stdio.h> 
  2. #include <linux/input.h>  
  3. #include <sys/types.h>  
  4. #include <sys/stat.h>  
  5. #include <fcntl.h>  
  6.   
  7. int main(int argc,char** argv)  
  8. {  
  9.     int keys_fd;  
  10.     char ret[2];  
  11.     struct input_event t;  
  12.     keys_fd=open(argv[1],O_RDONLY);  
  13.     if(keys_fd<=0)  
  14.     {     
  15.         printf("error\n");  
  16.         return -1;   
  17.     }     
  18.     while(1)  
  19.     {     
  20.         read(keys_fd,&t,sizeof(struct input_event));  
  21.         if(t.type==1)  
  22.             printf("key %i state %i \n",t.code,t.value);  
  23.     }     
  24.     close(keys_fd);  
  25.     return 0;  
  26. }  

3、键盘事件效果:

0 0