Detect when screensaver activates with Cocoa
Is there a way to trigger an action when the Mac OS X s开发者_开发技巧creensaver activates or when it goes to sleep (preferably using cocoa)?
You can register for various distributed notifications—on 10.6, I'm seeing com.apple.screenIsLocked/screenIsUnlocked and com.apple.screensaver.didstart/willstop/didstop. (Older versions of Mac OS X may not have all of these notifications.) You can observe the notifications as they occur with Notification Watcher.
Also see this answer.
Quick snippet using swift:
NSDistributedNotificationCenter.defaultCenter().addObserver(
self,
selector: "screenIsLocked:",
name: "com.apple.screenIsLocked",
object: nil)
with self being the observer you want to register, selector being the function handler, name being the notification name, and object the optional notification sender where if specified only notifications from this sender are passed on to the observer.
Also note that you can pass nil as the name and receive the whole bunch of notifications sent and not just the one specified.
PS: there are many notifications you can subscribe to, so make sure you know which object they're members of to be able to use them. For example check out NSDistributedNotificationCenter, NSNotificationCenter and NSWorkspace notifications.
swift 4:
DistributedNotificationCenter.default().addObserver(self, selector: #selector(screenIsLocked(_:)), name: Notification.Name("com.apple.screenIsLocked"), object: nil)
handler:
@objc func screenIsLocked(_ notification: Notification) {
// do stuff here
}
精彩评论