An AppleScript to move all windows to the main display

Oct 23, '07 07:30:02AM

Contributed by: JonLaliberte

The following AppleScript will move all windows which are offscreen to the main screen. This is useful when you have disconnected an external display, and the windows you had open on that screen (or screens) are now unreachable.

Copy and paste this code into Script Editor:

-- Example list of processes to ignore: {"xGestures"} or {"xGestures", "OtherApp", ...}
property processesToIgnore : {}

-- Get the size of the Display(s), only useful if there is one display
-- otherwise it will grab the total size of both displays
tell application "Finder"
  set _b to bounds of window of desktop
  set screen_width to item 3 of _b
  set screen_height to item 4 of _b
end tell

tell application "System Events"
  set allProcesses to application processes
  set _results to ""
  repeat with i from 1 to count allProcesses
    set doIt to 1
    repeat with z from 1 to count processesToIgnore
      if process i = process (item z of processesToIgnore) then
        set doIt to 0
      end if
    end repeat
    
    if doIt = 1 then
      tell process i
        repeat with x from 1 to (count windows)
          set winPos to position of window x
          set _x to item 1 of winPos
          set _y to item 2 of winPos
          
          if (_x < 0 or _y < 0 or _x > screen_width or _y > screen_height) then
            
            set position of window x to {0, 22}
            
          end if
        end repeat
        
      end tell
    end if
  end repeat
end tell

The definitely works in 10.4, and it may also work on OS 10.3. You can find a link to the original source in this blog entry.

[robg adds: You'll need to have the Enable Access for Assistive Devices box checked in Universal Access. The above-linked blog entry contains info on how to exclude certain apps from the script -- for use with programs that hide windows offscreen. Also, if there are updates to the script, they'll be found there, not here. I have not tested this one.]

Comments (8)


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