10.5: Find current Space number via AppleScript

Mar 04, '08 07:30:04AM

Contributed by: chucky23

One drag about Apple's Spaces implementation in Leopard is that there is no way to access Spaces via AppleScript. While you can use AppleScript to select indvidual spaces by simulating keystrokes, it'd be nice to have some way to find what the current space is via AppleScript.

Well, using PreFab Software's excellent UIBrowser, I was able to figure out how to accomplish that precise task with AppleScript.

(I believe you'll need to check Enable Access for Asssistive Devices in the Universal Access pane of System Preferences, if you haven't already, for this to work. You'll also need the Spaces menubar extra to be visible, which you can enable in the Spaces pane of System Preferences.)

The script will return the variable theCurrentSpace with the number of the currently displayed space. You can use that information in any way your scripting or automation imagination desires. Here is the AppleScript; copy and paste into Script Editor:

set xxVar to 0
tell application "System Events"
  tell process "SystemUIServer"
    set xVar to value of attribute "AXChildren" of menu bar 1
    set cVar to count of xVar
    repeat with iVar from 1 to cVar
      set zVar to value of attribute "AXDescription" of item iVar of xVar
      try
        if zVar = "spaces menu extra" then
          set xxVar to iVar
          exit repeat
        end if
      end try
    end repeat
  end tell
end tell
if xxVar = 0 then
  display dialog "Spaces Menu Extra not installed"
else
  tell application "System Events"
    tell process "SystemUIServer"
      set theCurrentSpace to value of menu bar item xxVar of menu bar 1
    end tell
  end tell
  
  -- Do what you want with "theCurrentSpace" variable starting here
  get theCurrentSpace as number
  -- Do what you want with "theCurrentSpace" variable ending here
  
end if
[robg adds: I haven't tested this one.]

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080227075244778