题
我需要得到在Mac使用的Xcode屏幕上的鼠标位置。我有一些代码,据说这是否但我总是返回x和y为0:
void queryPointer()
{
NSPoint mouseLoc;
mouseLoc = [NSEvent mouseLocation]; //get current mouse position
NSLog(@"Mouse location:");
NSLog(@"x = %d", mouseLoc.x);
NSLog(@"y = %d", mouseLoc.y);
}
我在做什么错了?你怎么在屏幕上的当前位置? 此外,最终该位置(保存在NSPoint)需要被复制到一个CGPoint与另一个函数一起使用,所以我需要得到这个无论是作为x,y坐标或翻译此。
解决方案 2
CGEventRef ourEvent = CGEventCreate(NULL);
point = CGEventGetLocation(ourEvent);
CFRelease(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);
其他提示
作者的原代码不工作,因为他/她试图打印浮出为%d。正确的代码将是:
NSPoint mouseLoc = [NSEvent mouseLocation]; //get current mouse position
NSLog(@"Mouse location: %f %f", mouseLoc.x, mouseLoc.y);
您不必去碳做到这一点。
当心NS环境与CG的环境混合。如果你与NS mouseLocation方法获得鼠标位置,然后使用CGWarpMouseCursorPosition(cgPoint),你将不会被发送到您所期望的屏幕上的点。从CG问题结果使用左上角为(0,0),而NS使用左下为(0,0)。
在这个问题的答案中的夫特强>
let currentMouseLocation = NSEvent.mouseLocation()
let xPosition = currentMouseLocation.x
let yPosition = currentMouseLocation.y
NSLog(@"%@", NSStringFromPoint(point));
的NSLog是真实的;
不隶属于 StackOverflow