可可:获取当前鼠标在屏幕上的位置

won*_*rer 28 mouse cocoa position

我需要使用Xcode在Mac上的屏幕上显示鼠标位置.我有一些代码应该这样做,但我总是将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);    

}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?你如何获得屏幕上的当前位置?此外,最终该位置(保存在NSPoint中)需要复制到CGPoint以与另一个函数一起使用,因此我需要将其作为x,y坐标或转换它.

Mar*_*Wan 56

作者的原始代码不起作用,因为他/她试图以%d打印浮点数.正确的代码是:

NSPoint mouseLoc = [NSEvent mouseLocation]; //get current mouse position
NSLog(@"Mouse location: %f %f", mouseLoc.x, mouseLoc.y);
Run Code Online (Sandbox Code Playgroud)

你不需要去Carbon这样做.

  • 那是Quartz事件服务,而不是Carbon,但除此之外你是正确的:Cocoa可以很好地完成这项工作,而无需创建CGEvent对象. (4认同)

won*_*rer 24

CGEventRef ourEvent = CGEventCreate(NULL);
point = CGEventGetLocation(ourEvent);
CFRelease(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);
Run Code Online (Sandbox Code Playgroud)

  • 别忘了发布CGEventRef! (7认同)

小智 12

注意将NS环境与CG环境混合.如果使用NS mouseLocation方法获取鼠标位置,则使用CGWarpMouseCursorPosition(cgPoint),您将不会被发送到您期望的屏幕上的点.问题的结果是CG使用左上角为(0,0),而NS使用左下角为(0,0).


And*_*dam 5

Swift中这个问题的答案

let currentMouseLocation = NSEvent.mouseLocation()
let xPosition = currentMouseLocation.x
let yPosition = currentMouseLocation.y
Run Code Online (Sandbox Code Playgroud)