How to lock screen from command line on a Mac

Interesting enough, there is no easier way than do a little “programming”. I found the following solution on http://apple.stackexchange.com/questions/80058/lock-screen-command-one-liner/123738#123738:

Creating “main.m” by any text editor:

#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 _lockScreenMenuHit:NULL];

    return 0;
}

Then compile it with clang (from Xcode):

1
clang -framework Foundation main.m -o lock

Then run the “lock” will lock your screen immediately.

Posted in Mac

Leave a Comment