【问题标题】:Moving mouse cursor with CGDisplayMoveCursor not working as expected when moving between monitors在监视器之间移动时,使用 CGDisplayMoveCursor 移动鼠标光标无法按预期工作
【发布时间】:2021-05-18 17:21:40
【问题描述】:

所以我需要能够将鼠标移动到任何给定点(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... 函数一起使用。或者最好的方法是什么。

【问题讨论】:

    标签: swift macos mouse


    【解决方案1】:

    你的代码的这个 sn-p:

    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 是窗口系统坐标空间(描述这两个窗口框架的坐标空间)中的一个点。

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

    本地显示空间中的点的坐标。原点是指定显示的左上角。

    所以我认为您需要获取您的point,并将其转换为相对于您所需显示的原点:

    let pointRelativeToScreen = point - monitor.frame.origin
    
    if CGDisplayMoveCursorToPoint(monitor.directDisplayId, pointRelativeToScreen) == CGError.failure { ... }
    

    另外,可能还有一些其他 API 需要以窗口系统坐标表示的光标点,这会自动将光标放置到正确的屏幕上。我现在无法访问 Xcode,所以我无法自己检查。

    【讨论】:

    • 是的,成功了。我以为我很好地阅读了文档,但显然我没有。谢谢你。我也尝试过 CGEvent 来创建一个 .mouseMove 事件,但这似乎只在主屏幕上有效?虽然我很沮丧,我可能做得不对。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多