我正在尝试让NSEvent停止侦听本地事件。是否有一种方法可以在创建事件后访问它?(这是我在removeEvent
中失败的尝试)
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello(event:))
}
func sayHello(event: NSEvent) -> NSEvent {
print("Welcome")
return event
}
@IBAction func removeEvent(_ sender: NSButton) {
let event = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello(event:))
NSEvent.removeMonitor(event)
}
创建一个指向事件监视器的引用,在视图控制器中添加一个实例属性,然后用按钮动作删除它:
var monitor: Any?
func sayHello(_ event: NSEvent) -> NSEvent {
print(#function)
return event
}
override func viewDidLoad() {
super.viewDidLoad()
monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello)
}
@IBAction func removeEvent(_ sender: NSButton) {
if let monitor = monitor {
NSEvent.removeMonitor(monitor)
}
}