Lock screen by API in macOS

后端 未结 8 1865
梦如初夏
梦如初夏 2020-12-12 16:49

Is there an API, that can lock the screen as the menu bar entry you can add from Keychain preferences?

This Keychain function is (was) lock

相关标签:
8条回答
  • 2020-12-12 17:28

    The following code does exactly what the Keychain menu item does since it just calls that. I used to use this (on 10.11 and 10.12), but this now fails on 10.13 (public beta) because there is no Keychain.menu nor menu item at all anymore. Mecki's answer is a working substitute but doesn't fade out the screen so it's really lower level.

    void lock() {
        NSBundle *bundle = [NSBundle bundleWithPath:@"/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu"];
        Class principalClass = [bundle principalClass];
        id instance = [[principalClass alloc] init];
        [instance performSelector:@selector(_lockScreenMenuHit:) withObject:nil];
    }
    
    0 讨论(0)
  • 2020-12-12 17:31

    I don't see anything documented as such, but the menu uses the ScreenSaver framework, which defines this:

    @interface ScreenSaverDefaults : NSUserDefaults 
    {
    @private
        NSMutableDictionary     *_defaults;
        NSMutableDictionary     *_registeredDefaults;
        NSString                *_userName;
        NSString                *_domainName;
        BOOL                    _dirty;
        BOOL                    _screenLockPrefChanged;
    }
    
    + (id) defaultsForModuleWithName:(NSString *)inModuleName;
    
    @end
    
    0 讨论(0)
提交回复
热议问题