Skip to content

Instantly share code, notes, and snippets.

@graywolf336
Created February 19, 2026 16:20
Show Gist options
  • Select an option

  • Save graywolf336/bc94d0f298f0103fbe3b5c00dd8fe7d5 to your computer and use it in GitHub Desktop.

Select an option

Save graywolf336/bc94d0f298f0103fbe3b5c00dd8fe7d5 to your computer and use it in GitHub Desktop.
A script for MacOS 15 to assist with capturing screenshots of windows. I use this with Claude Code to help usage generate documentation.
#!/bin/zsh
# capture-window.sh - Screenshot a specific app window on macOS
#
# Usage: capture-window.sh <app-name> [output-file]
# Examples:
# capture-window.sh "Google Chrome"
# capture-window.sh "Google Chrome" ~/Desktop/chrome.png
set -euo pipefail
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <app-name> [output-file]" >&2
exit 1
fi
APP_NAME="$1"
OUTPUT="${2:-screenshot_$(date +%Y%m%d_%H%M%S).png}"
# Activate the app to bring its window to the front
osascript -e "tell application \"${APP_NAME}\" to activate"
sleep 0.5
# Get the frontmost window ID via CoreGraphics.
# Uses a small Swift script since CoreGraphics C functions aren't
# accessible from JXA. The app name is passed via env var to avoid
# shell quoting issues.
_TMPFILE=$(mktemp)
trap 'rm -f "$_TMPFILE"' EXIT
cat > "$_TMPFILE" <<'SWIFT'
import CoreGraphics
import Foundation
let appName = ProcessInfo.processInfo.environment["APP_TARGET"] ?? ""
guard let list = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { exit(1) }
for w in list {
if let name = w["kCGWindowOwnerName"] as? String,
let layer = w["kCGWindowLayer"] as? Int,
let num = w["kCGWindowNumber"] as? Int,
name == appName, layer == 0 {
print(num)
break
}
}
SWIFT
WINDOW_ID=$(APP_TARGET="$APP_NAME" swift "$_TMPFILE" 2>/dev/null)
if [[ -z "$WINDOW_ID" ]]; then
echo "Error: No window found for '${APP_NAME}'" >&2
echo "Make sure the app is running and has a visible window." >&2
exit 1
fi
# -l <id> capture a specific window by its CGWindowID
screencapture -l "$WINDOW_ID" "$OUTPUT"
echo "Saved: $OUTPUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment