Skip to content

Instantly share code, notes, and snippets.

@freespace
Created October 28, 2011 11:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freespace/1322095 to your computer and use it in GitHub Desktop.
Save freespace/1322095 to your computer and use it in GitHub Desktop.
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
click
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
else
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.universalaccess"
display dialog "UI element scripting is not enabled. Check \"Enable access for assistive devices\""
end tell
end if
end tell
@EarMaster
Copy link

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