I need to set the position of the mouse on the screen. In some other similar question, it was suggested to use CGDisplayMoveCursorToPoint(CGDirectDisplayID display, CG
Here's a way to do it:
// coordinate at (10,10) on the screen
CGPoint pt;
pt.x = 10;
pt.y = 10;
CGEventRef moveEvent = CGEventCreateMouseEvent(
NULL, // NULL to create a new event
kCGEventMouseMoved, // what type of event (move)
pt, // screen coordinate for the event
kCGMouseButtonLeft // irrelevant for a move event
);
// post the event and cleanup
CGEventPost(kCGSessionEventTap, moveEvent);
CFRelease(moveEvent);
This will move the cursor to point (10,10) on screen (the upper left, next to the Apple menu).
Here's a Swift version, just for kicks:
let pt = CGPoint(x: 100, y: 10)
let moveEvent = CGEventCreateMouseEvent(nil, .MouseMoved, pt, .Left)
CGEventPost(.CGSessionEventTap, moveEvent);
The real answer to this question is:
CGMainDisplayID()
https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/index.html#//apple_ref/c/func/CGMainDisplayID
CGDisplayMoveCursorToPoint(CGMainDisplayID(), point);
Try CGWarpMouseCursorPosition()
. It doesn't require a display ID.
If you want a display ID, you can pick an element, using whatever criteria you like, from the array returned by [NSScreen screens]
. Invoke -deviceDescription
on that NSScreen
object. From the dictionary that's returned, invoke -objectForKey:
with the key @"NSScreenNumber"
.
Swift 3 version of the answer that helped me:
let pt = CGPoint(x: 100, y: 10)
let moveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved,
mouseCursorPosition: pt, mouseButton: .left)
moveEvent?.post(tap: .cgSessionEventTap)