2

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?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Noitidart
  • 35,443
  • 37
  • 154
  • 323

2 Answers2

1

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())
markroxor
  • 5,928
  • 2
  • 34
  • 43
  • Interesting thank you! But what about if user is not running screen saver, but has locked computer? – Noitidart Jan 11 '19 at 11:10
  • 1
    @noitidart although I have updated my answer but this part is already answered here - https://stackoverflow.com/questions/52750812/detecting-lock-screen-on-mac-through-python3/54141481#54141481 – markroxor Jan 12 '19 at 03:22
  • 1
    Thank you @markroxor! I was hoping for a non-quartz method, but I have accepted your solution. – Noitidart Jan 12 '19 at 14:12
0

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)" ?

Community
  • 1
  • 1
Noitidart
  • 35,443
  • 37
  • 154
  • 323