Cocoa: Getting the current mouse position on the screen

江枫思渺然 提交于 2019-11-28 06:48:43
MarcWan

The author's original code does not work because s/he is attempting to print floats out as %d. The correct code would be:

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

You don't need to go to Carbon to do this.

wonderer
CGEventRef ourEvent = CGEventCreate(NULL);
point = CGEventGetLocation(ourEvent);
CFRelease(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);

Beware mixing the NS environment with the CG environment. If you get the mouse location with the NS mouseLocation method then use CGWarpMouseCursorPosition(cgPoint) you will not be sent to the point on the screen you expected. The problem results from CG using top left as (0,0) while NS uses bottom left as (0,0).

The answer to this question in Swift

let currentMouseLocation = NSEvent.mouseLocation()
let xPosition = currentMouseLocation.x
let yPosition = currentMouseLocation.y
NSLog(@"%@", NSStringFromPoint(point));

NSLog is true;

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