The Awesome Guy
The Awesome Guy

Reputation: 332

Programmatically control a Mac cursor in Objective-C

There are a bunch of apps on the App Store that allow you to control your Mac's cursor - you install the app on your iPhone and some client software on your Mac, and then as you move your finger around on your phone and it controls your Mac through bluetooth.

My question is, how is this done? Not on the iOS side, but on the Mac side. How do you programmatically change the position of the cursor on a Mac?

Thanks in advance :)

Upvotes: 4

Views: 6089

Answers (2)

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

As stated by @H2C03, you can do that via CGWarpMouseCursorPosition(), however you will only be able to warp the mouse location every 250 milliseconds (0.25 seconds). In order to get around that, you have to add a bit of extra code in order to continuously warp the mouse.

NSPoint mouseWarpLocation = NSMakePoint(100, 100);

CGEventSourceRef evsrc = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventSourceSetLocalEventsSuppressionInterval(evsrc, 0.0);
CGAssociateMouseAndMouseCursorPosition (0);
CGWarpMouseCursorPosition(mouseWarpLocation);
CGAssociateMouseAndMouseCursorPosition (1);
CFRelease(evsrc);

Upvotes: 9

user529758
user529758

Reputation:

CoreGraphics can do it - specifically, you're looking for the CGWarpMouseCursorPosition() function. Quartz (CoreGraphics) display services documentation here.

Example: move the cursor to the center of the screen:

CGDirectDisplayID displayID = CGMainDisplayID();
size_t screenWidth = CGDisplayPixelsWide(displayID);
size_t screenHeight = CGDisplayPixelsHigh(displayID);
CGPoint centerOfScreen = CGPointMake(screenWidth / 2, screenHeight / 2);
CGWarpMouseCursorPosition(centerOfScreen);

Upvotes: 1

Related Questions