使用 [NSEvent mouseLocation] 的位置错误

이민규*_*이민규 5 macos cocoa objective-c nsevent ios

我为 Mac 制作了一个 iPhone 远程鼠标控制器应用程序:iPhone 应用程序将坐标值发送到 Mac,然后 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
          ........
Run Code Online (Sandbox Code Playgroud)

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

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

我不知道为什么会发生这种情况,该怎么办以及如何调试。

tsd*_*ter 6

您可以通过以下方法获得正确的 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
      ........
Run Code Online (Sandbox Code Playgroud)

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

NSRect screenRect = [[NSScreen mainScreen] frame];
NSInteger height = screenRect.size.height;
Run Code Online (Sandbox Code Playgroud)

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

temp.y = height - mouseLoc.y; // right value
Run Code Online (Sandbox Code Playgroud)

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


Bum*_*imp 2

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