用C语言在Linux下获取鼠标指针的相对位置

手册/FAQ (499) 2016-04-19 13:46:46

1. 关于"/dev/input/mice"
相信很多人都用过Linux,也许你发现不管是在X-window下面,还是在Console下面,鼠标都是可以操作的。那么你有没有考虑过这些鼠标都是从哪来的?

不错!他们都是从"/dev/input/mice"这个文件里来的。如果你对Linux比较熟,那么你肯定看得出来这是一个设备文件。"mice"就是Linux下面鼠标的设备文件,不管你用的是PS2的还是USB的,所有关于鼠标的操作都被抽象到"mice"这个文件中。

2. "mice"之母
在linux下面,她是"mousedev.c"这个文件。你可以在内核的"Drivers/input"目录里找到她。在她那里,你可以得到关于"mice"的一切。

3. 坐标
如何得到mouse的当前坐标值?可通过如下几步:

1)打开"/dev/input/mice"文件。

2)读3个字节。三个字节的值分别是“Button类型”,“X的相对位移”,“Y的相对位移”。这里先用Button, xRel, yRel表示。

3)取Button的低3位(Button & 0x07)。0x00 = LeftButtonUp, 0x01 = LeftButtonDown, 0x02 = RightButtonDown.

4)因为这里取得是相对位移,所以X, Y要分别与上一次的坐标值相加。xPos += xRel; yPos +=yRel.

  • #include <stdio.h>    
  • #include <stdlib.h>    
  • #include <linux/input.h>    
  • #include <fcntl.h>    
  • #include <sys/time.h>    
  • #include <sys/types.h>    
  • #include <sys/stat.h>    
  • #include <unistd.h>    
  •     
  •     
  • int main(int argc,char **argv)    
  • {    
  •     int fd, retval;    
  •     char buf[6];    
  •     fd_set readfds;    
  •     struct timeval tv;    
  •     // 打开鼠标设备    
  •     fd = open( "/dev/input/mice", O_RDONLY );    
  •     // 判断是否打开成功    
  •     if(fd<0) {    
  •         printf("Failed to open \"/dev/input/mice\".\n");    
  •         exit(1);    
  •     } else {    
  •         printf("open \"/dev/input/mice\" successfuly.\n");    
  •     }    
  •     
  •     while(1) {    
  •         // 设置最长等待时间    
  •         tv.tv_sec = 5;    
  •         tv.tv_usec = 0;    
  •     
  •         FD_ZERO( &readfds );    
  •         FD_SET( fd, &readfds );    
  •     
  •         retval = select( fd+1, &readfds, NULL, NULL, &tv );    
  •         if(retval==0) {    
  •             printf( "Time out!\n" );    
  •         }    
  •         if(FD_ISSET(fd,&readfds)) {    
  •             // 读取鼠标设备中的数据    
  •             if(read(fd, buf, 6) <= 0) {    
  •                 continue;    
  •             }    
  •             // 打印出从鼠标设备中读取到的数据    
  •             printf("Button type = %d, X = %d, Y = %d, Z = %d\n", (buf[0] & 0x07), buf[1], buf[2],   buf[3]);    
  •         }    
  •     }    
  •     close(fd);    
  •     return 0;    
  • }    
THE END