I want to write a program that would run in the background and log pointer's position when a mouse click occured. I tried to search for it in Google, but results were for NCurses and some GUI libraries. Is there any way that I could write a program that listens to mouse events in the background? C and/or Python ways are prefered.
Asked
Active
Viewed 1.8k times
8
-
1[Yes there is](http://www.gnu.org/software/xnee/). – n. m. could be an AI Jan 27 '13 at 23:43
-
@n.m. Seems promising. Trying it out. – yasar Jan 27 '13 at 23:54
-
http://stackoverflow.com/a/14556353/841108 – Basile Starynkevitch Jan 28 '13 at 06:20
2 Answers
15
Here is an example for logging mouse position, clicks and releases:
#include <stdio.h>
#include <X11/Xlib.h>
char *key_name[] = {
"first",
"second (or middle)",
"third",
"fourth", // :D
"fivth" // :|
};
int main(int argc, char **argv)
{
Display *display;
XEvent xevent;
Window window;
if( (display = XOpenDisplay(NULL)) == NULL )
return -1;
window = DefaultRootWindow(display);
XAllowEvents(display, AsyncBoth, CurrentTime);
XGrabPointer(display,
window,
1,
PointerMotionMask | ButtonPressMask | ButtonReleaseMask ,
GrabModeAsync,
GrabModeAsync,
None,
None,
CurrentTime);
while(1) {
XNextEvent(display, &xevent);
switch (xevent.type) {
case MotionNotify:
printf("Mouse move : [%d, %d]\n", xevent.xmotion.x_root, xevent.xmotion.y_root);
break;
case ButtonPress:
printf("Button pressed : %s\n", key_name[xevent.xbutton.button - 1]);
break;
case ButtonRelease:
printf("Button released : %s\n", key_name[xevent.xbutton.button - 1]);
break;
}
}
return 0;
}
Compile it using:
$ gcc mouse.c -o mouse -lX11
$ ./mouse
Mouse move : [664, 395]
Mouse move : [665, 393]
Mouse move : [666, 393]
Mouse move : [666, 392]
Mouse move : [664, 392]
Mouse move : [664, 393]
Mouse move : [664, 395]
Button pressed : first
Button released : first
Button pressed : third
Button released : third
^C
$
Look also here Keyboard and Pointer Events and there are a lot of information in The Xlib Manual.

Alex Spurling
- 54,094
- 23
- 70
- 76
-
2I know this is old but for persons coming here in the future. Now the order of parameters passed to `gcc` matters. `gcc -lX11 mouse.c -o mouse` won't work, you have to put `-lX11` at the end, so: `gcc mouse.c -o mouse -lX11` – Jhon Pedroza Jun 24 '18 at 04:59
-
1@JhonPedroza thanks - I've edited the answer with this new parameter ordering. – Alex Spurling Feb 03 '21 at 18:16
0
similar question: How can I capture mouseevents and keyevents using python in background on linux
The above answer is using python binding for evdev. this binding is available for capturing mouse event.