Ben Ben - 1 month ago 20
Python Question

Controlling the mouse from Python in OS X

What would be the easiest way to move the mouse around (and possibly click) using python on OS X?

This is just for rapid prototyping, it doesn't have to be elegant.

Thanks!

Ben Ben
Answer

I dug through the source code of Synergy to find the call that generates mouse events:

#include <ApplicationServices/ApplicationServices.h>

int to(int x, int y)
{
    CGPoint newloc;
    CGEventRef eventRef;
    newloc.x = x;
    newloc.y = y;

    eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
                                        kCGMouseButtonCenter);
    //Apparently, a bug in xcode requires this next line
    CGEventSetType(eventRef, kCGEventMouseMoved);
    CGEventPost(kCGSessionEventTap, eventRef);
    CFRelease(eventRef);

    return 0;
}

Now to write Python bindings!