AppleScript to Toggle the Desktop

Here’s an AppleScript I use to quickly toggle desktop visibility for taking screenshots and recording screencasts. Thought I’d share it with the world.

Copy and paste the code below into AppleScript Editor, or your editor of choice, compile and save.

As always, scripts like this work best using FastScripts from Red Sweater Software.

on run
    tell application "System Events"
        set _activeApp to name of the first process whose frontmost is true
    end tell
    try
        set _theVar to ((do shell script "defaults read com.apple.finder CreateDesktop") as integer) as boolean
    on error -- if the default value doesn't already exist, create it...
        do shell script "defaults write com.apple.finder CreateDesktop 1"
        set _theVar to ((do shell script "defaults read com.apple.finder CreateDesktop") as integer) as boolean
    end try
    do shell script "defaults write com.apple.finder CreateDesktop " & (((not _theVar) as integer) as string)
    tell application "Finder" to quit
    delay 1
    tell application "Finder" to launch
    tell application _activeApp to activate
end run

Note: This single script turns off the desktop if it’s on, and turns it on if it’s off – just to clear up the question should it need to be asked.

  • GUido

    I ve used the stopy bout i cant toggle on my desktop again HElp!

    • http://jimmitchell.org Jim Mitchell

      Run the script again, it’ll toggle your desktop back on – hence “toggle” – as in “off” and “on”.

  • Pingback: Hide And Show Desktop Icons On OS X With An Automator Service | Lifehacker Australia()

  • http://newagelingo.com neeks

    It would be even nicer if you replace the last line with

    tell application “Finder” –selects application
    quit
    delay 2
    activate application “Finder”
    end tell

    This re opens the windows that were already open when calling the service.

    • http://jimmitchell.org Jim Mitchell

      Thanks for the suggestion, neeks.

      An even more elegant solution is to capture the frontmost app first, then hide the desktop, restart the finder, and then reactivate the app that was frontmost.

      I’ve updated the script to reflect that. Works great with FastScripts, too.

  • Brendan

    Thank you. Created and loaded into my Quicksilver catalog.