How to read low level mouse click position in linux .

前端 未结 2 673
春和景丽
春和景丽 2020-12-28 09:11

I am using this code to read mouse events from the dev/input/event* in linux .

#include 
#include 
#include 
         


        
相关标签:
2条回答
  • 2020-12-28 09:23

    You can get the initial position from X11, and use relative coordinates to track the pointer:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    #include <linux/input.h>
    #include <fcntl.h>
    #include <X11/Xlib.h>
    
    #define MOUSEFILE "/dev/input/event6"
    
    int main()
    {
      int fd;
      struct input_event ie;
      Display *dpy;
      Window root, child;
      int rootX, rootY, winX, winY;
      unsigned int mask;
    
      dpy = XOpenDisplay(NULL);
      XQueryPointer(dpy,DefaultRootWindow(dpy),&root,&child,
                  &rootX,&rootY,&winX,&winY,&mask); 
    
      if((fd = open(MOUSEFILE, O_RDONLY)) == -1) {
        perror("opening device");
        exit(EXIT_FAILURE);
      }
    
      while(read(fd, &ie, sizeof(struct input_event))) {
        if (ie.type == 2) {
          if (ie.code == 0) { rootX += ie.value; }
          else if (ie.code == 1) { rootY += ie.value; }
          printf("time%ld.%06ld\tx %d\ty %d\n", 
             ie.time.tv_sec, ie.time.tv_usec, rootX, rootY);
        } else if (ie.type == 1) {
          if (ie.code == 272 ) { 
            printf("Mouse button ");
            if (ie.value == 0)  
              printf("released!!\n");
            if (ie.value == 1)  
              printf("pressed!!\n");
        } else {
            printf("time %ld.%06ld\ttype %d\tcode %d\tvalue %d\n",
                ie.time.tv_sec, ie.time.tv_usec, ie.type, ie.code, ie.value);
        }
      }
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-28 09:33

    A mouse only sends relative movement, not absolute position. You have to keep track of it yourself, and when you receive a mouse-button event you have to check your own coordinates for the position.

    0 讨论(0)
提交回复
热议问题