Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting the display to sleep (⇧⌃⏏/shift+control+eject) in AppleScript

Is it possible to write an AppleScript to put the display to sleep (which locks the display if the computer is set to lock on sleep)? You can do this from the keyboard by entering ⌃⇧⏏ (shift+control+eject); this leaves all the programs, etc., running, and just turns off the screen.

like image 841
David Avatar asked Oct 09 '11 06:10

David


4 Answers

I've been wanting to do this for a while now. I just found out how in the man pages. You can use the following command to achieve instant display sleep. (I have tested it on OS X 10.10.)

pmset displaysleepnow

(no root privileges / sudo required!)

I'm not sure if this works for 10.9.4 yet but by all means give it a shot!

like image 161
user3064009 Avatar answered Jan 04 '23 12:01

user3064009


you can use: tell application "Finder" to sleep

Or use bettertouchtool. It is a small app which you can use native functions in addition to applescript.

like image 41
user3720218 Avatar answered Jan 04 '23 12:01

user3720218


do shell script "pmset displaysleepnow"
like image 25
IronDuck Avatar answered Jan 04 '23 12:01

IronDuck


Edit 2015-08-23: This is possible (from the shell) as of OS X 10.9! Go see user3064009's answer for the update :-)


There's no good way to do this; there's a SuperUser question about this same thing. Depending on why you want this, however, there's one workaround I know: activate the screen saver. (This is what they suggest over on SuperUser). You can do this in AppleScript with launch application id "com.apple.ScreenSaver.Engine", or from the command line by running the application /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine. I don't know whether or not this is technically documented anywhere, but it's worked for several iterations of the OS now. It may not do exactly what you want—your screen saver may, for instance, be colorful, which isn't helpful if you want a black screen—but it will be the same in that it does lock the screen if you have that set up.

For a nice catalog of other workarounds, check out this MacScripter thread: it documents that

  • There's no scriptable way to do this.
  • You can't tell AppleScript to key code EJECT, as there's no such key code.
  • You can use pmset to tell the display to go to sleep in one minute, but then you have to wait.
  • There's an undocumented IOKit way to do this; there's a mailing list post explaining how.
like image 33
Antal Spector-Zabusky Avatar answered Jan 04 '23 12:01

Antal Spector-Zabusky