Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Apple script to lock screen using keychain's menu item
Probe Menu Bar
This script uses UI element scripting to return a list of every menuitem
of every menu for every application currently running.
If "Enable access for assistive devices" is not checked,
this script will open the Universal Access System Preference and ask
the user to check the checkbox.
Copyright © 2007 Apple Inc.
You may incorporate this Apple sample code into your program(s) without
restriction. This Apple sample code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to
redistribute this Apple sample code as "Apple sample code" after having
made changes. If you're going to redistribute the code, we require
that you make it clear that the code was descended from Apple sample
code, but that you've made changes.
tell application "System Events"
get properties
get every process
if UI elements enabled then
tell process "SystemUIServer"
repeat with i from 1 to number of menu bar items of menu bar 1
if description of menu bar item i of menu bar 1 is "Keychain menu extra" then
tell menu bar item i of menu bar 1
if name of menu item 1 of front menu is "Lock Screen" then
click menu item "Lock Screen" of front menu
exit repeat
end if
end tell
end if
end repeat
end tell
tell application "System Preferences"
set current pane to pane ""
display dialog "UI element scripting is not enabled. Check \"Enable access for assistive devices\""
end tell
end if
end tell
Copy link

zaderade commented Jan 9, 2012

Thank you!!!!!!! People are looking everywhere for this.

Copy link

EarMaster commented Apr 1, 2015

The strings "Keychain menu extra" and "Lock Screen" are localized strings. So you have to edit them to fit to the language your system is running.

In German these strings are "Schlüsselbund-Menüerweiterung" and "Bildschirm schützen".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment