Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created June 29, 2011 17:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iloveitaly/1054346 to your computer and use it in GitHub Desktop.
Save iloveitaly/1054346 to your computer and use it in GitHub Desktop.
Take a Screenshot of the Frontmost / Active Window
-- Author: Michael Bianco
-- http://mabblog.com/
-- References:
-- http://stackoverflow.com/questions/1866912/applescript-how-to-get-current-display-resolution/6524651#6524651
-- http://macscripter.net/viewtopic.php?id=28958
on run argv
screenshot_active_window(item 1 of argv)
end run
on screenshot_active_window(outputPath)
set quotedPath to quoted form of outputPath
-- get screen dimensions
copy {do shell script "system_profiler SPDisplaysDataType | awk '/Resolution/{print $2}'", ¬
do shell script "system_profiler SPDisplaysDataType | awk '/Resolution/{print $4}'"} to {scrn_w, scrn_h}
tell application "System Events"
set proc to name of first process whose frontmost is true
tell window 1 of process proc
-- get window initial position
copy position to {ini_x, ini_y}
copy size to {win_w, win_h}
-- center window because the sips crop command automatically centers the cropped area in the image
set position to {(scrn_w - win_w) / 2, (scrn_h - win_h) / 2}
end tell
-- capture the screen , crop the image and open it.
do shell script "screencapture" & space & "-x" & space & quotedPath & "; sips -c" & space & (win_h) & space & (win_w) & space & quotedPath & space & "--out" & space & quotedPath & "; open" & space & quotedPath
-- revert window position
tell window 1 of process proc to set position to {ini_x, ini_y}
end tell
end screenshot_active_window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment