用C语言在linux下获取鼠标光标的相对位置

来源:互联网 发布:淘宝店铺的级别 编辑:程序博客网 时间:2024/04/29 20:16

转载的代码:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <linux/input.h>  
  4. #include <fcntl.h>  
  5. #include <sys/time.h>  
  6. #include <sys/types.h>  
  7. #include <sys/stat.h>  
  8. #include <unistd.h>  
  9.   
  10.   
  11. int main(int argc,char **argv)  
  12. {  
  13.     int fd, retval;  
  14.     char buf[6];  
  15.     fd_set readfds;  
  16.     struct timeval tv;  
  17.   
  18.     //fd = open("/dev/input/mice", O_RDONLY);  
  19.     if(( fd = open("/dev/input/mice", O_RDONLY))<0)  
  20.     {  
  21.         printf("Failed to open \"/dev/input/mice\".\n");  
  22.         exit(1);  
  23.     }  
  24.     else  
  25.     {  
  26.         printf("open \"/dev/input/mice\" successfuly.\n");  
  27.     }  
  28.   
  29.     while(1)  
  30.     {  
  31.         tv.tv_sec = 5;  
  32.         tv.tv_usec = 0;  
  33.   
  34.         FD_ZERO(&readfds);  
  35.         FD_SET(fd, &readfds);  
  36.   
  37.         retval = select(fd+1, &readfds, NULL, NULL, &tv);  
  38.         if(retval==0)  
  39.         printf("Time out!\n");  
  40.         if(FD_ISSET(fd,&readfds))  
  41.         {  
  42.             if(read(fd, buf, 6) <= 0)//终端设备,一次只能读取一行  
  43.             {  
  44.                 continue;  
  45.             }  
  46.             printf("Button type = %d, X = %d, Y = %d, Z = %d\n", (buf[0] & 0x07), buf[1], buf[2],   buf[3]);  
  47.         }  
  48.     }  
  49.     close(fd);  
  50.     return 0;  
  51. }