Search code examples
objective-cmacoscocoacore-graphicscore-foundation

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?


Solution

  • 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())