malkomalko
11/27/2011 - 10:06 PM

Center the top most window using AppleScript

Center the top most window using AppleScript

#!/usr/bin/env bash
# Center the top most window using AppleScript
# I call this up quickly using Quicksilver and run it as a terminal
# script because (surprise!) it's faster than running as native AppleScript

osascript -e "
tell application \"Finder\"
  set screenSize to bounds of window of desktop
  set screenWidth to item 3 of screenSize
end tell

tell application \"System Events\"
  set myFrontMost to name of first item of (processes whose frontmost is true)
end tell

try
  tell application myFrontMost
    set windowSize to bounds of window 1
    set windowXl to item 1 of windowSize
    set windowYt to item 2 of windowSize
    set windowXr to item 3 of windowSize
    set windowYb to item 4 of windowSize
    
    set windowWidth to windowXr - windowXl
    
    set bounds of window 1 to {(screenWidth - windowWidth) / 2.0, 0, (screenWidth + windowWidth) / 2.0, (windowYb - windowYt)}
  end tell
end try
"