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, CGPoint point)
, but I cannot figure out how to get the CGDirectDisplayID
. Please tell me how to get the CGDirectDisplayID
or a different method to set the mouse position.
How can I set the mouse position?
Asked Answered
The real answer to this question is:
CGMainDisplayID()
CGDisplayMoveCursorToPoint(CGMainDisplayID(), point);
This worked for me. I also tried some of the swift solutions after converting them to the new syntax, but they no longer seem to work. –
Foretime
What's the difference between
CGMainDisplayID()
and kCGDirectMainDisplay
? –
Abuzz That’s the best solution, even for Swift developer. Thank you! –
Street
Surely that's "the real answer" only as soon as you can rid the world of second monitors? –
Immure
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"
.
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).
Does not work. For some reason, it sets the x of the mouse correctly, but if I try to change the Y, it flickers between the top and bottom of the screen. Even if I use the current position of the mouse. –
Intercom
I just tried it with a variety of
x
and y
values, and it moved to each of them. Are you posting any other events, or modifying this one, in some other fashion before posting it? –
Subchaser 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);
Swift 3 (and beyond) 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)
still valid in Swift 5 –
Actuality
© 2022 - 2024 — McMap. All rights reserved.