You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CGWarpMouseCursorPosition将光标移动到NSView中心位置

正确实现方案

你的问题核心是坐标体系不匹配:

  1. CGWarpMouseCursorPosition 使用的是 CoreGraphics 屏幕坐标系,原点在屏幕左上角,单位为点。
  2. NSView.frame 的坐标是相对于其父视图的坐标,contentView 的父容器是窗口,所以其 frame.origin 始终是相对于窗口左下角的偏移,不包含窗口本身在屏幕中的位置信息。
  3. AppKit 框架的默认坐标系 原点在左下角,和 CoreGraphics 的坐标系Y轴方向相反,需要额外做翻转。

完整可运行代码

override func mouseMoved(with event: NSEvent) {
    guard let window = window, 
          let view = window.contentView, 
          let screen = window.screen else { return }
    
    // 获取视图自身坐标系的中心点,使用bounds而非frame避免受父视图坐标影响
    let viewCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
    // 将视图坐标转换为窗口坐标系坐标
    let windowCenter = view.convert(viewCenter, to: nil)
    // 将窗口坐标转换为AppKit标准屏幕坐标(原点在屏幕左下角)
    let screenCenterAppKit = window.convertPoint(toScreen: windowCenter)
    // 翻转Y轴得到CoreGraphics坐标系下的坐标,供CGWarpMouseCursorPosition使用
    let screenCenterCG = CGPoint(
        x: screenCenterAppKit.x,
        y: screen.frame.height - screenCenterAppKit.y
    )
    
    CGWarpMouseCursorPosition(screenCenterCG)
    // 后续业务逻辑
}

场景优化建议(针对鼠标锁定类游戏)

  • 若需要持续锁定鼠标在中心点,建议调用 CGAssociateMouseAndMouseCursorPosition(false) 断开系统鼠标位移和光标位置的绑定,避免输入延迟,退出游戏/解锁鼠标时再调用 CGAssociateMouseAndMouseCursorPosition(true) 恢复系统默认行为。
  • 上述代码会自动适配窗口的位置、大小变化,不需要额外监听窗口回调更新计算逻辑。

内容的提问来源于stack exchange,提问作者CPlus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:30:01