2019-05-21: Updated with a note for macOS 10.13+.
2015-05-13: Updated with another Hammerspoon technique.
I’ve been searching for an OS X equivalent way of locking your screen with
something akin to Win+L
on Windows.
There are a lot of tutorials out there to do something similar, but aren’t
quite exactly the Windows-equivalent behavior.
(It’s kind of a shame that Apple hasn’t implemented this feature
natively.)
If you are using macOS 10.13 or newer, lock your screen with
Ctrl+Cmd+Q
.
If you’d like to script additional behavior when locking your screen, then the using something like Hammerspoon (and reading the rest of this page) might be useful.
hammerspoon (native)
Chris (cmsj) reached out to point me to a Hammerspoon function:
hs.caffeinate.lockScreen()
, which seems to be doing fast user switching.
In your Hammerspoon config ~/.hammerspoon/init.lua
, simply add the following
(modified to your preferences):
-- lock screen
hs.hotkey.bind({"cmd", "shift"}, "O", function()
hs.caffeinate.lockScreen()
end)
hammerspoon and lockscreen.m
Another way to lock your screen is to use Hammerspoon and building
and using a lockscreen
binary.
(I’m already using Hammerspoon for window management–see my config here.)
The lockscreen
program (courtesy of jnk @ StackOverFlow) is the equivalent
of clicking on the “Lock Screen” from the Keychain Access menu plugin
(discussed further below).
From StackOverflow, save the following to
main.m
:#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; }
Compile and save
lockscreen
to somewhere (e.g.,/Users/alice/bin/lockscreen
):clang -framework Foundation main.m -o lockscreen
Then, in your Hammerspoon config
~/.hammerspoon/init.lua
, we add the following to executelockscreen
with key combinationCmd+Shift+O
:-- lock screen hs.hotkey.bind({"cmd", "shift"}, "O", function() os.execute("/Users/alice/bin/lockscreen") end)
other ways to lock your screen
The following is useful if you can’t/don’t have Xcode or Hammerspoon:
Set a hot corner to sleep or activate the screen saver
Manually via Keychain Access (start Keychain Access, open preferences, and enable “Show keychain status in menubar”)
Use AppleScript and Automator (after adding Keychain Access to your menubar):
tell application "System Events" to tell process "SystemUIServer" to click (first menu item of menu 1 of ((click (first menu bar item whose description is "Keychain menu extra")) of menu bar 1) whose title is "Lock Screen")
Use Fast User Switching on the command-line:
/System/Library/CoreServices/Menu\ Extras/user.menu/Contents/Resources/CGSession -suspend