Programmatically lock the screen

Posted: June 5th, 2016 | Author: | Filed under: macOS, Programming | Tags: , , , | No Comments »

The Keychain Access application has a preference to display a “Lock Screen” menu item in the menubar:


Keychain Access Preferences

After enabling the checkbox ‘Show keychain status in menu bar’, this menu will appear in the menubar:


Lock Screen in Menubar

This menu is located here:

/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu

and it is fairly easy to find the method
-[AppleKeychainExtra _lockScreenMenuHit:].


-[AppleKeychainExtra _lockScreenMenuHit:]

That’s this simple! The method -[AppleKeychainExtra _lockScreenMenuHit:] simply calls the private method ‘SACLockScreenImmediate’ from the Login private framework. The Login framework takes care of all the hard work.

Now we can create a simple application to lock the screen. Here is the whole source code:

extern void SACLockScreenImmediate();

int main()
{
    SACLockScreenImmediate();
    return 0;
}

To compile it:

clang -F /System/Library/PrivateFrameworks -framework login -o LockScreen LockScreen.c

You can download the precompiled binary here: LockScreen.zip



Leave a Reply