Skip to content
avatar

Centering a Window Via AppleScript

John Siracusa recently lamented the loss of one of his classic OS add-ons; the ability to center the current window onscreen via a global key combo.

Well, the global key combo can be had in any number of ways, but here’s an AppleScript that’ll do it for you. It finds the screen size using the technique Craig Hockenberry showed to John Gruber, then finds the current frontmost window and resizes it. Saved as a Script into my Script Menu, it seems to work fine.


on run
tell application "System Events"
set fma to first process whose frontmost is true
end tell

tell application (name of fma)
set fmwBounds to bounds of first window
end tell

tell application "Finder"
set desktopBounds to bounds of window of desktop
end tell

set fmwWidth to (item 3 of fmwBounds) - (item 1 of fmwBounds)
set fmwHeight to (item 4 of fmwBounds) - (item 2 of fmwBounds)

set desktopWidth to (item 3 of desktopBounds) - (item 1 of desktopBounds)
set desktopHeight to (item 4 of desktopBounds) - (item 2 of desktopBounds)

set newX to (desktopWidth / 2) - (fmwWidth / 2)
set newY to (desktopHeight / 2) - (fmwHeight / 2)

set newBounds to {newX, newY, newX + fmwWidth, newY + fmwHeight}
tell application (name of fma)
set bounds of first window to newBounds
end tell
end run

{ 2 } Comments

  1. avatar Dave Hendrix | 2008-04-29 at 2:34 pm | Permalink

    Extra credit: multiple displays, various sizes, and not aligned to the same baseline. Hurts my head just thinking about it. Any way to do this without dipping into the window server prefs via “defaults read /Library/Preferences/com.apple.windowserver”? Probably sufficient to just center on main screen, but…

  2. avatar TALlama | 2008-04-29 at 11:35 pm | Permalink

    Yeah, I should have been more explicit; this will fail pretty miserably on multiple displays, for the reasons Gruber points out in the linked page. There doesn’t seem to be a very good way to find the desktop size on a multi-display setup without doing as you suggest and calling out to “defaults” on the command line. If anyone finds one, I’ll gladly update the script.