Programmatically changing screen lock timeout

蹲街弑〆低调 提交于 2020-01-05 07:48:06

问题


In my Cocoa application I would like to access and change the computer's screen lock timeout setting. Changing it in System Preferences does not require the user to enter the admin password.

Unfortunately I couldn't find any information in the documentation, and I'm not sure what topic I should look into (security settings / prefPane programming).
Any help would be appreciated.


回答1:


NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/Users/new/Library/Preferences/com.apple.screensaver.plist"];
[plistDict setObject:@"1" forKey:@"askForPassword"];
[plistDict setObject:@"3600" forKey:@"askForPasswordDelay"];
[plistDict writeToFile:@"/Users/new/Library/Preferences/com.apple.screensaver.plist" atomically:YES];  

or From terminal

defaults write com.apple.screensaver askForPasswordDelay 5



回答2:


The above answer apparently works for some, but on 10.8 it fails if you are using FileVault. The setting will stick, but it won't actually take effect until you launch System Preferences. Luckily, there's a way to 'touch' the setting after you are done:

- (void)touchSecurityPreferences;
{
    NSAppleScript *kickSecurityPreferencesScript = [[[NSAppleScript alloc] initWithSource: @"tell application \"System Events\" to tell security preferences to set require password to wake to true"] autorelease];
    [kickSecurityPreferencesScript executeAndReturnError:nil];
}

Edit Turns out this only works for going from a non-zero setting to zero setting. I assume this is a security thing. To go the other way, launching System Preferences is the only way.

Edit 2 Here's code for launching System Preferences, should you want to do so:

- (void)launchAndQuitSecurityPreferences;
{
    // necessary for screen saver setting changes to take effect on file-vault-enabled systems when going from a askForPasswordDelay setting of zero to a non-zero setting
    NSAppleScript *kickSecurityPreferencesScript = [[[NSAppleScript alloc] initWithSource:
                                                     @"tell application \"System Preferences\"\n"
                                                     @"     tell anchor \"General\" of pane \"com.apple.preference.security\" to reveal\n"
                                                     @"     activate\n"
                                                     @"end tell\n"
                                                     @"delay 0\n"
                                                     @"tell application \"System Preferences\" to quit"] autorelease];
    [kickSecurityPreferencesScript executeAndReturnError:nil];
}


来源:https://stackoverflow.com/questions/10713651/programmatically-changing-screen-lock-timeout

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