Search code examples
clinuxinputkeyboard

Linux: Canceling input from /dev/input/event*


In a program I've been developing, I want to read keyboard strokes independently of whatever window I'm focused on (so, the same program will work whether I'm focused on Firefox or whether I'm playing Minecraft, without having to change focus). So far, using the linux/input.h library and reading from /dev/input/event5 seems to work pretty well.

fd = open(argv[1], O_RDONLY);
struct input_event ev;
int len = read(fd, &ev, sizeof(struct input_event));

However, one feature I would like to add is canceling this input while the program is running, preventing my keystrokes from reaching Firefox or Minecraft or the general OS. Is there a good way to do that?


Solution

  • Warning: untested

    • open the character device with mode O_RDWR (read/write)
    • grab the device: ioctl(fd, EVIOCGRAB, 1)
    • read events
    • if you want to dispatch the event:
      • ungrab device ioctl(fd, EVIOCGRAB, 0)
      • write event

    Between the ungrab and the write, other events could occur, which will not filtered and dispatched to all connected file handles. I don't know if it is possible to write first and ungrab afterwards (or even write at all, check the return value of write).

    Hint: You could also modify libevdev.