Noitidart
Noitidart

Reputation: 37338

Test if screensaver is running or workspace is locked

On Mac OS X, I know in Cocoa I can set up a observer for detecting future screen saver events or workspace lock events, like this:

- (id)init {
   if ((self = [super init])) {
      NSDistributedNotificationCenter* distCenter =
           [NSDistributedNotificationCenter defaultCenter];
      [distCenter addObserver:self
                    selector:@selector(onScreenSaverStarted:)
                        name:@"com.apple.screensaver.didstart"
                      object:nil];
      [distCenter addObserver:self
                    selector:@selector(onScreenSaverStopped:)
                        name:@"com.apple.screensaver.didstop"
                      object:nil];
      [distCenter addObserver:self
                    selector:@selector(onScreenLocked:)
                        name:@"com.apple.screenIsLocked"
                      object:nil];
      [distCenter addObserver:self
                    selector:@selector(onScreenUnlocked:)
                        name:@"com.apple.screenIsUnlocked"
                      object:nil];
   }
   return self;
}

But before I add these observers, is there any way to test if a screensaver is running, or if the workspace is locked?

Upvotes: 2

Views: 1226

Answers (2)

markroxor
markroxor

Reputation: 6506

You can check if the screensaver is running by checking if the ScreenSaverEngine process is running or not, by using -

pgrep ScreenSaverEngine

you can try it by using -

while true
do
pgrep ScreenSaverEngine
sleep 1
done

and then turning on the screensaver.


For checking the lockscreen -
Install quartz -
pip install pyobjc-framework-Quartz

Much simple code -

import Quartz
d = Quartz.CGSessionCopyCurrentDictionary()
print('CGSSessionScreenIsLocked' in d.keys())

Upvotes: 1

Noitidart
Noitidart

Reputation: 37338

I found a partial solution: OSX: check if the screen is locked

Issue with this method though is it thinks its locked the moment the screensaver comes on, even if you have "require password delay" set to something greater than immediately. Anyone know of a way to differentiate between "just screensaver being on" and "screensaver on and locked (as in now mouse move will show password screen)" ?

Upvotes: 0

Related Questions