M to the K
M to the K

Reputation: 1586

OSX: Lock the screen programmatically

I'm looking for a way to lock the user screen programmatically without putting the Mac asleep. Right now, i'm able to trigger the lock screen with the kAESleep event but it's more a hack and it put the computer asleep. Is it possible ? Thanks

Upvotes: 3

Views: 1879

Answers (3)

Michael Altfield
Michael Altfield

Reputation: 2777

I was successfully able to lock the screen on macOS in python with the following

import ctypes, ctypes.util

login = ctypes.CDLL( '/System/Library/PrivateFrameworks/login.framework/login' )
login.SACLockScreenImmediate()

I discovered this by scarce information on the Internet and trial-and-error. As far as I know, Apple doesn't document the SACLockScreenImmediate() function at all.

If anyone can find the official reference documentation for the "Login Framework" library, please drop it in the comments :)

Source

The is used in the BusKill app, which locks the screen when a magnetic breakaway connection in a USB Dead Man Switch is severed:

Upvotes: 0

Janne Jalkanen
Janne Jalkanen

Reputation: 134

The following AppleScript will do it for you. Note that because of security limitations of OSX, AppleScript pauses for five seconds before it executes an UI function, so it takes a small while to function. I'm using Quicksilver to bind it to a hotkey.

(As a bonus, this script will also pause a couple of your music players. Feel free to remove those lines.)

#
#  Tell our noisy programs to shut up
#
tell application "Spotify"
    pause
end tell

tell application "iTunes"
    pause
end tell

#
#  Lock up the screen without going to sleep.  Needs that Keychain Access
#  is set up properly.
#
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")

You will need to set up Keychain Access so that it has the lock icon on screen though.

Upvotes: 0

Sean Baker
Sean Baker

Reputation: 664

Configure the screensaver to require a password immediately after it starts, then start the screensaver programmatically. I have it programmed to a keyboard shortcut to help my Windows folks transition to using real computers ;).

Upvotes: 1

Related Questions