5

I have referred to a lot of tutorials on how to control your mouse cursor's movements and clicks by map these events to your own real mouse, but I noticed that everytime I must associate this mouse to one specified event in /dev/input/, if I didn't connect one real mouse, or if the linux didn't give the right event number on this real mouse, the program will definitely fail.

Now I need to write a generalized program which can make one complete virtual mouse on linux, that is to say, this program can be applied to any machine even the machine don't actually have one mouse, but the cursor will react as long as I give them the distance, the direction the mouse cursor move, the click it takes and how long this click lasts.

So I just wonder is there any general interface which don't require a real mouse device I must map to, I have tried to access /dev/input/mice event, but it seems that I can only get cursor's location and click information as long as it moves or clicks, could anyone tell me a more general interface? Thank U in advance!!!

Danny.Dong
  • 51
  • 1
  • 2

2 Answers2

5

You could use the XTest functions. This X11 extension includes functions to fake key presses, mouse button presses and mouse movement.

You can read the man page here: http://linux.die.net/man/3/xtestfakekeyevent

This short C example, when linked with -lX11 and -lXtst, should move the mouse to the upper left corner of the screen and click the left mouse button:

#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>

void move_mouse(Display* display, int x, int y){
    XTestFakeRelativeMotionEvent(display, x, y, 0);
    XFlush(display);
}
void set_mouse(Display* display, int x, int y){
    XTestFakeMotionEvent(display, 0, x, y, 0);
    XFlush(display);
}
void button_make(Display* display, unsigned int button){
    XTestFakeButtonEvent(display, button, True, 0);
    XFlush(display);
}
void button_break(Display* display, unsigned int button){
    XTestFakeButtonEvent(display, button, False, 0);
    XFlush(display);
}
int main(int argc, char **argv){
    Display *display = XOpenDisplay(NULL);
    set_mouse(display, 0, 0);
    button_make(display, 1);
    button_break(display, 1);
    return 0;
}
Chris Smeele
  • 966
  • 4
  • 8
  • Any idea how to perform such task without the necessity of using external libraries/tools? – Jewenile Jul 22 '17 at 17:42
  • @Jewenile I think you're stuck with at least X libraries. XTest is an extension that's installed on most X servers I've encountered. For a simpler commandline interface you could also look at `xdotool`, but it's still a tool you'd have to install. – Chris Smeele Jul 24 '17 at 06:33
1

See this related question.

Assuming an X11 desktop environment, you could use XSendEvent ; however recieveing applications can discriminate such "fake" events.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547