0

I'm not sure as to what keywords I should use to search this, so I'm going to ask here. I'm sorry if that's a duplicate.

Basically, I'd like to do the following

./my_prog &

where my_prog, coded in C++14,

  • adds a character to file A whenever I right click.
  • adds a character to file B whenever I left click.
  • adds a character to file C whenever I press a key.

(That would enable me to see how often I do any of the above at the end of the day.)

First I wanted to use Qt but I realized soon afterwards that Qt does that in its own window only. (Or at least, that's as far as I can use it.) That wouldn't help as I'd rather have my_prog count every single click and key-press.

Anyone know what library/functions I should use? Thanks.

Law.
  • 75
  • 7
  • You'd like a [KeyLogger](http://en.wikipedia.org/wiki/Keystroke_logging) ? – hlscalon May 06 '15 at 16:38
  • Yes, sort of. But I want to code it myself, unless that's way too complicated. – Law. May 06 '15 at 16:40
  • 1
    It's more complicated than just calling a function. You'd need to intercept the event in the OS or the interrupt and let that event or interrupt pass through, while you log the event/interrupt to your background application. In other words, it's a system level functionality, not application level. – lurker May 06 '15 at 16:42
  • 1
    possible duplicate of [How to listen for mouse events in Linux?](http://stackoverflow.com/questions/14553435/how-to-listen-for-mouse-events-in-linux) – Captain Giraffe May 06 '15 at 16:47
  • I can't get why this overly broad question (basically asking for code samples) was upvored? – πάντα ῥεῖ May 06 '15 at 16:47
  • I'm still willing to read about that. Would you know what websites/documentation I should read? – Law. May 06 '15 at 16:48

1 Answers1

0

You need to read your mouse device in Linux. In my Ubuntu that device is '/dev/input/event4', you can check yours from '/proc/bus/input/devices'.

In linux/input.h header you can find 'input_event' struct which can be used to handle different mouse events.

Here is simple example

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

#define MOUSEFILE "/dev/input/event4"

int main()
{
  int fd;
  struct input_event ie;

 if((fd = open(MOUSEFILE, O_RDONLY)) == -1) {
    perror("Cannot access mouse device");
     exit(EXIT_FAILURE);
      }
 while(read(fd, &ie, sizeof(struct input_event))) {
   printf("%d, %d, %d\n", ie.type, ie.value, ie.code);
 }
 return 0;

}

You can find out more about input_event struct and code definitions from http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/include/linux/input.h?v=2.6.11.8

For example in my machine I realized that when I left click my mouse the following combination occurs

ie.type = 1
ie.value = 1
ie.code = 272

This can be helpful to catch different events in Linux.

Ashot Khachatryan
  • 2,156
  • 2
  • 14
  • 30