Test if screensaver is running or workspace is locked

旧时模样 提交于 2020-01-15 06:22:12

问题


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?


回答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())



回答2:


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



来源:https://stackoverflow.com/questions/27514778/test-if-screensaver-is-running-or-workspace-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!