Quick tip: AppleScript application toggle
From my hat full of stupid Mac tricks:
I use a lesser-known (and very old) program called Spark for defining most of the keyboard shortcuts on my system. I have a shortcut for every one of my most regularly-used applications, plus shortcuts for various AppleScripts, shell scripts, system functions, etc. I know there are more recent applications which do the same thing, but I’ve had everything set up in Spark for ages and it still works a treat. Seriously, if you want an application launcher, it’s worth checking out (and free). However, you can use this tip in any app which lets you assign a hotkey to an AppleScript (FastScripts, BetterTouchTool).
So, anyway, I’ve grown to like applications which have a system-wide hotkey that toggles them between foreground and hidden. It makes a lot of sense for certain applications which you check and then move on from. Sparrow, Twitter, etc. I wanted that functionality in more apps, so I run this as the AppleScript in Spark, replacing the app name with whatever I want to toggle.
set appName to "Mail" set appID to bundle identifier of (info for (path to application appName)) tell application "System Events" if not (exists process appName) then tell application appID to activate else if frontmost of process appName then set visible of process appName to false else set frontmost of process appName to true end if end if end tell
Sorry about the Thanks to D Curtis and Zettt in the comments, I’ve put together a more elegant script. It does the same thing without shelling out, and the syntax is cleaned up. Thanks guys!
do shell script for launching the app. I’m really lazy about replacing more than one instance of a variable, and “tell application appName” doesn’t work, even with various “using terms from” attempts. Know how to fix that? Let me know.
One more update: after some testing, it looks like D Curtis’ first script below is much faster for some reason (I’m assuming that getting the “bundle identifier of (info for (path to application appName))” takes some extra resources). I recommend going with this one instead, but I’m leaving both up for reference:
set appName to "Mail" set startIt to false tell application "System Events" if not (exists process appName) then set startIt to true else if frontmost of process appName then set visible of process appName to false else set frontmost of process appName to true end if end tell if startIt then tell application appName to activate end if