Fork me on GitHub

article

AppleScript to Detect Displays on Snow Leopard

October 6, 2010 | Computers

One of the things about having a laptop and continually connecting and disconnecting from an external display is having to tell the system to detect the external (and sometimes the internal) display so that both displays are running. Simply detecting displays doesn’t seem to be an easily scriptable system event. I finally got an AppleScript cobbled together so that I can simply launch this AppleScript from LaunchBar (you Quicksilver users can do the same thing).

This is based off of code that I’ve written as well as code that I found on Apple’s AppleScript mailing list and should be adaptable to most menu-bar items.

  1.  to click_menu_extra at menu_list
  2.   tell application "System Events" to tell process "SystemUIServer"'s menu bar 1
  3.   click (first menu bar item whose value of attributes contains menu_list's beginning)
  4.   repeat with item_name in rest of menu_list
  5.   click (first menu item of result's menu 1 whose name is item_name)
  6.   delay 0.5
  7.   end repeat
  8.   end tell
  9.  end click_menu_extra
  10.  
  11.  click_menu_extra at {"displays", "Detect Displays"}

The key part that took a while to figure out in there is the delay right after the menu item click. The system just didn’t like everything happening so fast and on a whim I tried the delay and it worked.

This works with OS X 10.6 Snow Leopard. It seems that in every major release since about 10.4 Apple has changed something about the syntax for reaching menu-bar items so I don’t expect this to work on previous versions of OS X.

Update 2011-11-21: This script continues to work fine on Lion. For those that prefer a Gist to copy from, you can do that here.

4 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  • Thanks, but it doesn’t work for me:

    error “System Events got an error: Can’t get menu bar item 1 of menu bar 1 of process \”SystemUIServer\” whose value of every attribute contains \”displays\”. Invalid index.” number -1719

    Justin, December 2, 2010 4:43 pm | permalink

  • Ah. You have to have Displays set to “Show Displays in Menu Bar”. Otherwise this script will error out.

    Justin, December 2, 2010 4:47 pm | permalink

  • Yeah, that’s the rub – there’s no real programmatic way to do this in OS X so this applescript literally clicks the menu item for you…

    Shawn, December 2, 2010 5:17 pm | permalink

Mentions

  1. AppleScript的初体验,用它切换输入法 « 我的新家

    […] AppleScript to Detect Displays on Snow Leopard […]

    January 29, 2011 | 7:33 am

Comments are closed