Programmatically lock the screen

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

After enabling the checkbox Show keychain status in menu bar, this menu will appear in the 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:].

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: