This article proposes a technic to programmatically lock the screen.

  • Easily preview Mermaid diagrams
  • Live update when editing in your preferred editor
  • Capture screenshots with customizable margins
  • Create PNG from the Terminal
  • Free download on the Mac App Store
MarkChart

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