我想在鼠标移动15秒后随时显示通知。
到目前为止,我似乎明白我需要添加
window.acceptsMouseMovedEvents = true
我需要覆盖鼠标移动
override func mouseMoved(with event: NSEvent) {
//print ("MOVED!")
timer.invalidate()
displayNotification()
}
func displayNotification(){
var timeLeft = 15
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
let notification = NSUserNotification()
notification.title = "Title of notification"
notification.subtitle = "Subtitle of notification"
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.default.deliver(notification)
timeLeft -= 1
if(timeLeft==0){
timer.invalidate()
}
}
}
我似乎无法让mouseMoved部分正常工作。
这花了我很长时间,但我终于想明白了,我错过了这篇文章:
NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { _ in
self.displayNotification()
}
我唯一的问题是:计时器不会正确地使我移动鼠标的任何时间无效。