Lock screen from command-line as same as Keychain Access does on OS X
cocoa, macos
Solution
I just found a solution for this: https://apple.stackexchange.com/a/123738/72534
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
int main () {
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];
return 0;
}
Save as `lockscreen.m` and compile with:
clang -framework Foundation -o lockscreen lockscreen.m
Works perfectly, as it just calls the same routine as the status bar icon.
Problem
I noticed that `/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend` and Keychain Access's Lock Screen (open its Preferences, check 'Show keychain status in menu bar' then hit Lock Screen from the status bar icon.) has different functionality. Is there any way to run Keychain Access's Lock Screen from command-line through Terminal.app or Cocoa API? Mac OS 10.9. Thanks!