October 29, 2009 at 8:09 PM by Dr. Drang
That one-liner suspend script I discussed last week has been working fine, but it was missing one feature: it didn’t put the display to sleep. Now, it’s easy enough to put the display to sleep with the system-provided ⌃⇧⏏ (Control-Shift-Eject), but I really wanted to both suspend the user session and sleep the display with just one keystroke combination. Eventually, I worked it out.
You might think UI scripting in AppleScript would allow you to do something like
key code XXX using control down shift down
but there doesn’t seem to be a key code for the Eject key. (I’m certain there is a key code for Eject, but it looks like the system eats it before AppleScript can see it.)
Searching for other ways to put the display to sleep, I came across an application with the made-for-Google name of SleepDisplay. It’s what you might call a highly focused app: launch it and your display goes to sleep; jiggle the mouse or touch a key and your display wakes up as the app quits.
So here’s my AppleScript for suspending and sleeping:
1: do shell script "/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend" 2: delay 10 3: launch application "SleepDisplay.app"
I have FastScripts set up to run this when triggered by ⌃⌥⌘F19 (Control-Option-Command-F19).
The delay in Line 2 is essential. I first wrote and tested the script without it and found myself staring at a locked-up computer. AppleScript runs its commands asynchronously; it doesn’t wait for
CGSession -suspend command to finish before launching SleepDisplay, and that somehow screws things up. I can’t say a full 10 seconds of delay is necessary, but it works, and I don’t see any reason to hunt down the minimum delay time.
Clark, of Clark’s Tech Blog fame, has a different way to get the display to sleep. He uses the built-in
pmset (power management set) command to temporarily override the display sleep settings in the Energy Saver Preference Page. Like
pmset is Unix-style command that Apple created for OS X and which provides much or all of the functionality of a more familiar GUI tool. I didn’t know it existed until I read Clark’s post.
I still like the immediacy of DisplaySleep;
pmset can’t put your screen to sleep in less than a minute. But it’s a good command to know. I’m thinking I can use its
noidle option to create a Caffeine-like command that won’t take up space in my iBook’s crowded menubar.