X11 Fake Mouse Events Generation using XTest Extension

In one of the old post, I discussed about the Fake Key Event generation program. After a few weeks, we found that, in one specific application, it is not possible to do all operation using keyboard and one specific operation needs right mouse click. So I add the fake mouse event generation also using XTest extension. Here I am sharing a simple example program, which may help to understanding the API.

/* fakeMouse.c */
#include <X11/extensions/XTest.h>
#include <unistd.h>
int main (){
  Display *dpy = NULL;
  XEvent event;
  dpy = XOpenDisplay (NULL);
  /* Get the current pointer position */
  XQueryPointer (dpy, RootWindow (dpy, 0), &event.xbutton.root,
   &event.xbutton.window, &event.xbutton.x_root,
   &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y,
   &event.xbutton.state);

  /* Fake the pointer movement to new relative position */
  XTestFakeMotionEvent (dpy, 0, event.xbutton.x + 100,
  event.xbutton.y + 50, CurrentTime);
  XSync(dpy, 0);
  sleep(3);

  /* Fake the pointer movement to new absolate position */
  XTestFakeMotionEvent (dpy, 0, 250, 250, CurrentTime);
  sleep(3);

  /* Fake the mouse button Press and Release events */
  XTestFakeButtonEvent (dpy, 3, True,  CurrentTime);
  XTestFakeButtonEvent (dpy, 3, False, CurrentTime);
  XCloseDisplay (dpy);
  return 0;
}

Build and Run this program:
$ gcc fakeMouse.c -o fakeMouse -lX11 -lXtst -lXext
$ ./fakeMouse

Mouse Button Mappings: The 2nd argument in XTestFakeButtonEvent() represent the specific mouse button. You can map 8 mouse buttons (1 – Left, 2 – Middle, 3 – Right, 5 – Scroll,..).

9 thoughts on “X11 Fake Mouse Events Generation using XTest Extension

  1. Great you posted that. You’re the only source I found on the internet in that matter. Thanks.Sorry for bad english.

  2. Thanks Subramanian, Thats really useful for me. As I am new to X11 programming. This is a quick start for me.

Leave a comment