使用[NSEvent mouseLocation]的错误位置

时间:2011-11-20 14:15:56

标签: objective-c ios nsevent

我为Mac制作了一个iphone远程鼠标控制器应用程序:iPhone应用程序将坐标值发送到Mac,然后处理鼠标位置值。

要获取Mac上的当前鼠标位置,接收器会调用[NSEvent mouseLocation]。

x的值始终是正确的,但y的值是错误的。

我使用“while”循环来处理此事件。

while (1) {
    mouseLoc = [NSEvent mouseLocation];

    while ((msgLength = recv(clientSocket, buffer, sizeof(buffer), 0)) != 0) {
          CGPoint temp;
          temp.x = mouseLoc.x;
          temp.y = mouseLoc.y; // wrong value
          ........

每个循环周期的y值不同。例如,y值在第一次循环时为400,在下一次循环时y为500;然后在下一个循环中y再次为400。

鼠标指针连续上下移动,两个不同y值的总和始终为900.(我认为因为屏幕分辨率为1440 * 900。)

我不知道它为什么会发生,该怎么做,以及如何调试它。

4 个答案:

答案 0 :(得分:3)

这是一种可以获得正确Y值的方法:

while (1) {
mouseLoc = [NSEvent mouseLocation];
NSRect screenRect = [[NSScreen mainScreen] frame];
NSInteger height = screenRect.size.height;

while ((msgLength = recv(clientSocket, buffer, sizeof(buffer), 0)) != 0) {
      CGPoint temp;
      temp.x = mouseLoc.x;
      temp.y = height - mouseLoc.y; // wrong value
      ........

基本上,我抓住了屏幕高度:

NSRect screenRect = [[NSScreen mainScreen] frame];
NSInteger height = screenRect.size.height;

然后我取屏幕高度并从中减去mouseLocation的Y坐标,因为mouseLocation从底部/左侧返回坐标,这将从顶部给出Y坐标。

temp.y = height - mouseLoc.y; // right value

这可以在我的应用程序中控制鼠标位置。

答案 1 :(得分:2)

我不知道为什么在没有看到更多代码的情况下它会发生变化,但很有可能它与mouseLoc = [NSEvent mouseLocation];返回原点位于左下角的点这一事实有关屏幕的,而不是通常的左上角。

答案 2 :(得分:1)

获取正确的位置代码:

CGPoint mousePoint = CGPointMake([NSEvent mouseLocation].x, [NSScreen mainScreen].frame.size.height - [NSEvent mouseLocation].y);

答案 3 :(得分:0)

斯威夫特 5:

let mousePosition = CGPoint(x: NSEvent.mouseLocation.x, y: (NSScreen.main?.frame.size.height)! - NSEvent.mouseLocation.y)