gpt4 book ai didi

macos - 在 Swift 中获取鼠标坐标

转载 作者:IT王子 更新时间:2023-10-29 05:26:00 25 4
gpt4 key购买 nike

这里是 Swift 新手。

我一直在处理一项本应微不足道的任务时遇到麻烦。我想要做的就是获取鼠标光标的 x,y 坐标按需。我宁愿不要等待鼠标移动事件触发,然后才能获取指针的坐标。

非常感谢任何帮助!

最佳答案

你应该看看 NSEvent 方法 mouseLocation

编辑/更新:Xcode 11 • Swift 5.1

如果您想在您的应用处于事件状态时监视任何窗口上的事件,您可以添加一个 LocalMonitorForEvents 匹配 mouseMoved 掩码,如果它不处于事件状态,则添加一个 GlobalMonitorForEvents。请注意,您需要将窗口属性 acceptsMouseMovedEvents 设置为 true

import Cocoa

class ViewController: NSViewController {
lazy var window: NSWindow = self.view.window!
var mouseLocation: NSPoint { NSEvent.mouseLocation }
var location: NSPoint { window.mouseLocationOutsideOfEventStream }
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) {
print("mouseLocation:", String(format: "%.1f, %.1f", self.mouseLocation.x, self.mouseLocation.y))
print("windowLocation:", String(format: "%.1f, %.1f", self.location.x, self.location.y))
return $0
}
NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { _ in
print(String(format: "%.0f, %.0f", self.mouseLocation.x, self.mouseLocation.y))
}
}
override func viewWillAppear() {
super.viewWillAppear()
window.acceptsMouseMovedEvents = true
}
}

Sample project

关于macos - 在 Swift 中获取鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com