Is there a way to trigger an action when the Mac OS X screensaver 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With