Automating Window Screenshots (without GUI Scripting)

Some days ago I needed to automatically take screenshots of certain windows in order to visually document the results of several maintenance scripts running on our production Macs.

As I am required to avoid GUI Scripting and the built in screencapture command only allows to automatically take screenshots of the entire main screen, I wrote my own little foundation tool to help me out. It simply cuts out the image defined by the given window bounds from the screenshot and saves it to a new file.

The script works just fine and so I decided to share it with you. Maybe someone else can also make good use of it. To demonstrate its usage I created two sample AppleScripts, Me In A Window and Spotshot.

Me In A Window activates the Address Book application, selects your own card, takes a screenshot of the window and displays the result with the Preview application.

Spotshot asks you to provide a search string, then opens a corresponding Spotlight Search Window, waits a few seconds and finally takes a screenshot of the window and displays it with the Preview application.

You can download all scripts together here:

Automating Window Screenshot - Sample Scripts (ca. 182.7 KB)

The scripts were tested with both Intel and PowerPC based Macs running Mac OS X 10.4.11 and 10.5.7. Please note that there are separate Spotshot scripts for both Mac OS X 10.4 and Mac OS X 10.5, because of the different Spotlight implementation in each OS version.

Hint: Some applications don’t support AppleScript and so you cannot easily get their window bounds. But very often applications save their window bounds in their preferences file. For example, Spotlight does it in Mac OS X 10.4:

defaults read SearchWindow
→ returns “{{914, -221}, {781, 823}}” on my Mac

You can have a look at the Spotshot script for Mac OS X 10.4 to learn more about this.

All the AppleScripts rely on some foundation tools I wrote:

Cuts out an image by the specified rectangle

Displays the sizes of the available screens

Displays a Spotlight Search Window initialized with the given search string

Happy Screenshooting!