Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when screensaver activates with Cocoa

Is there a way to trigger an action when the Mac OS X screensaver activates or when it goes to sleep (preferably using cocoa)?

like image 215
chrisbdaemon Avatar asked May 02 '10 03:05

chrisbdaemon


2 Answers

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.

like image 165
Nicholas Riley Avatar answered Sep 23 '22 01:09

Nicholas Riley


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.

like image 35
Joseph Junior Sfeir Avatar answered Sep 23 '22 01:09

Joseph Junior Sfeir