在显示器之间移动时,使用 CGDisplayMoveCursor 移动鼠标光标无法按预期工作

Moving mouse cursor with CGDisplayMoveCursor not working as expected when moving between monitors

所以我需要能够将鼠标移动到任何给定点(x 和 y)。我正在尝试使用 CGDisplayMoveCursor 来完成此操作,同时它会移动光标但不会将其放置在我期望的位置。我的设置中有两台显示器。我通过 NSScreen.screens[i].frame 获取框架,这些是他们的框架。

Built-in Retina Display
NSRect (0.0, 0.0, 1440.0, 900.0)

SwitchResX4 - LG HDR WQHD
NSRect (-1186.0, 900.0, 3840.0, 1600.0)

然后,当我收到新点时,我使用 NSRect.contains(NSPoint) 来查找两个监视器中的哪一个包含该点。该部分按预期工作。

但后来我想将光标移动到那个点,但它并没有像您预期的那样工作(光标移动但没有移动到您根据帧预期的点)。这是相关代码。

let point = NSPoint(x: x, y: y)
guard let monitor = Monitor.displayIdWithPoint(point) else {
      SendlogCallbackEvent("D", "", "Found nil in monitor with point", #function, #file, #line)
 }      
 if CGDisplayMoveCursorToPoint(monitor.directDisplayId, point) == CGError.failure {
     SendlogCallbackEvent("D", "", "CGError.failer to move cursor", #function, #file, #line)
  }

我读到它可能与 CG 和 NS 如何以不同方式处理坐标系有关,但我一直无法弄清楚如何使其工作。我如何“转换”我的 NSPoint 到 CGPoint 以便它与 CGDisplayMove... 功能一起使用。或者最好的方法是什么。

您的这段代码:

let point = NSPoint(x: x, y: y)
guard let monitor = Monitor.displayIdWithPoint(point) else {
      SendlogCallbackEvent("D", "", "Found nil in monitor with point", #function, #file, #line)
}

给我的印象是你正在查找的 point 是 window 系统坐标 space 中的一个点(坐标 space 其中两个window 帧被描述)。

但是查看 CGDisplayMoveCursorToPoint(_:_:) 的文档,我们看到(强调我的):

point

The coordinates of a point in local display space. The origin is the upper-left corner of the specified display.

所以我认为您需要对 point 进行转换,使其相对于所需显示的原点:

let pointRelativeToScreen = point - monitor.frame.origin

if CGDisplayMoveCursorToPoint(monitor.directDisplayId, pointRelativeToScreen) == CGError.failure { ... }

或者,可能还有一些其他 API 需要用 window 系统坐标表示的光标点,它会自动为您将其显示在正确的屏幕上。我现在无法访问 Xcode,所以我无法自己检查。