OSX Click the mouse via code
A few weeks ago I needed to be able to click the mouse via code on my MacBook. After some digging I came across this article, which provided some useful basic code.
I quickly got fed up of having to work out the screen coordinates so have extended the application to use the current coordinates of the mouse. Here’s the code.
// File:
// click.m
//
// Compile with:
// gcc -o click click.m -framework ApplicationServices -framework Foundation -framework AppKit
//
// Usage:
// ./click -x pixels -y pixels -clicks Number Of Clicks - interval wait between clicks
// At the given coordinates it will click and release.
#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
// Wait 5 seconds before getting the mouse location, give
// the user a chance.
sleep(5);
// Grabs command line arguments -x, -y, -clicks, -interval.
// If not set, it'll use the current mouse location for coordinates
// and 1 for the click count and interval.
int x = [args integerForKey:@"x"];
int y = [args integerForKey:@"y"];
int clicks = [args integerForKey:@"clicks"];
int interval= [args integerForKey:@"interval"];
if (x == 0 || y == 0)
{
CGEventRef ourEvent = CGEventCreate(NULL);
CGPoint ourLoc = CGEventGetLocation(ourEvent);
x = ourLoc.x;
y = ourLoc.y;
}
if (clicks == 0)
{
clicks = 1;
}
if (interval == 0)
{
interval = 1;
}
// The data structure CGPoint represents a point in a two-dimensional
// coordinate system. Here, X and Y distance from upper left, in pixels.
CGPoint pt;
pt.x = x;
pt.y = y;
// This is where the magic happens. See CGRemoteOperation.h for details.
//
// CGPostMouseEvent( CGPoint mouseCursorPosition,
// boolean_t updateMouseCursorPosition,
// CGButtonCount buttonCount,
// boolean_t mouseButtonDown, ... )
//
// So, we feed coordinates to CGPostMouseEvent, put the mouse there,
// then click and release.
//
int i = 0;
for (i = 0; i < clicks; i++ )
{
CGPostMouseEvent( pt, 1, 1, 1 );
CGPostMouseEvent( pt, 1, 1, 0 );
// Wait interval.
sleep (interval);
}
[pool release];
return 0;
}
You’ll need XCode installed to build it (if you’re desperate for a binary, drop me an e-mail). You can then run with -clicks 375 -interval 4, you then have 5 seconds to place your mouse on the area of the screen where it’ll click.