如何设置鼠标位置?

问题描述:

我需要在屏幕上设置鼠标的位置。在其他一些类似的问题,有人建议使用CGDisplayMoveCursorToPoint(CGDirectDisplayID display, CGPoint point),但我不知道如何获得CGDirectDisplayID。请告诉我如何获取CGDirectDisplayID或另一种设置鼠标位置的方法。如何设置鼠标位置?

这里有一个办法做到这一点:

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

这将光标移动到屏幕上的点(10,10)(左上角,旁边的苹果菜单)。

+0

不起作用。出于某种原因,它正确设置了鼠标的x,但是如果我尝试更改Y,它会在屏幕的顶部和底部之间闪烁。即使我使用鼠标的当前位置。 – 2012-04-22 22:29:21

+0

我只是用各种各样的'x'和'y'值试了一下,并把它移到了它们中的每一个。在发布之前,您是否以其他方式发布任何其他活动或修改此活动? – 2012-04-22 23:02:16

尝试CGWarpMouseCursorPosition()。它不需要显示器ID。

如果你想要一个显示ID,你可以从[NSScreen screens]返回的数组中选择一个元素,使用你喜欢的任何标准。在NSScreen对象上调用-deviceDescription。从返回的字典中,使用密钥@"NSScreenNumber"调用-objectForKey:

真正的这个问题的答案是:

CGMainDisplayID() 

https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/index.html#//apple_ref/c/func/CGMainDisplayID

CGDisplayMoveCursorToPoint(CGMainDisplayID(), point); 

这里有一个雨燕的版本,只是踢:

let pt = CGPoint(x: 100, y: 10) 
let moveEvent = CGEventCreateMouseEvent(nil, .MouseMoved, pt, .Left) 
CGEventPost(.CGSessionEventTap, moveEvent); 

斯威夫特3版本的答案是帮我:

let pt = CGPoint(x: 100, y: 10) 

let moveEvent = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, 
mouseCursorPosition: pt, mouseButton: .left) 

moveEvent?.post(tap: .cgSessionEventTap)