How can I set the mouse position?

北城余情 提交于 2019-12-18 07:11:50

问题


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.


回答1:


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);



回答2:


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".




回答3:


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).




回答4:


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);



回答5:


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)


来源:https://stackoverflow.com/questions/10255995/how-can-i-set-the-mouse-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!