2015年8月3日 星期一

偵測 keyboard event & mouse/touchpad coordinates

偵測 keyboard event

linux/input.h

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>

int main ()  
{  
  int keys_fd;  
  char ret[2];  
  struct input_event t;  
  
  keys_fd = open ("/dev/input/event15", O_RDONLY);  
  if (keys_fd <= 0)  
    {   
      printf ("open /dev/input/event15 device error!\n");  
      return 0;  
    }   
  
  while (1)  
    {   
      if (read (keys_fd, &t, sizeof (t)) == sizeof (t))  
        {
          if (t.type == EV_KEY)  
            if (t.value == 0 || t.value == 1)  
        {
              printf ("key %d %s\n", t.code,  (t.value) ? "Pressed" : "Released");  
          if(t.code==KEY_ESC)  
              break;  
        }
        }
    }   
  close (keys_fd);  
  
  return 0;  
}
結果: (記得sudo or su)

key 28 Released
key 32 Pressed
key 32 Released

ref:流星的博客

mouse/touchpad coordinates

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>

#define EVENT_DEVICE    "/dev/input/event0"
#define EVENT_TYPE      EV_ABS
//#define EVENT_CODE_X    ABS_X //mouse
//#define EVENT_CODE_Y    ABS_Y
#define EVENT_CODE_X    ABS_MT_POSITION_X //Multi-Touch
#define EVENT_CODE_Y    ABS_MT_POSITION_X

int main(int argc, char *argv[])
{
    struct input_event ev;
    int fd;
    char name[256] = "Unknown";

    if ((getuid ()) != 0) {
        fprintf(stderr, "You are not root! This may not work...\n");
        return EXIT_SUCCESS;
    }

    /* Open Device */
    fd = open(EVENT_DEVICE, O_RDONLY);
    if (fd == -1) {
        fprintf(stderr, "%s is not a vaild device\n", EVENT_DEVICE);
        return EXIT_FAILURE;
    }

    /* Print Device Name */
    ioctl(fd, EVIOCGNAME(sizeof(name)), name);
    printf("Reading from:\n");
    printf("device file = %s\n", EVENT_DEVICE);
    printf("device name = %s\n", name);

    for (;;) {
        const size_t ev_size = sizeof(struct input_event);
        ssize_t size;

        /* TODO: use select() */

        size = read(fd, &ev, ev_size);
        if (size < ev_size) {
            fprintf(stderr, "Error size when reading\n");
            goto err;
        }

        if (ev.type == EVENT_TYPE && (ev.code == EVENT_CODE_X
                      || ev.code == EVENT_CODE_Y)) {
            /* TODO: convert value to pixels */
            printf("%s = 0x%x\n", ev.code == EVENT_CODE_X ? "X" : "Y", ev.value);
        }
    }

    return EXIT_SUCCESS;

err:
    close(fd);
    return EXIT_FAILURE;
}

ref :
1. stackoverflow
2. Kernel Input Event Overview

other keyword:
1. screen coordinates
2. client-area coordinates

沒有留言:

張貼留言