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,

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

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

  /* 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,..).

Tagged with: ,
Posted in Uncategorized
8 comments on “X11 Fake Mouse Events Generation using XTest Extension
  1. M.K. Sondej says:

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

  2. Bharathi Subramanian says:

    Thanks and happy to see my post is useful for someone 🙂

  3. Praveen says:

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

  4. Per says:

    Thanks for code example, it contains all that I need to get started! :o)

  5. Herman says:

    Thanks!!! I really appreciate your post, faking events was exactly what I needed!!!

  6. ad84 says:

    thank you, that was very useful.

  7. kenn says:

    Thank you! I was looking for such an example.

  8. Anilr says:

    Thanks helped me a lot.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: