2

I am creating a 'Quit All' keyboard shortcut. I have the Quit All Applications system command and the AppleScript to close open Finder windows (without it, Finder windows stay open). However, if no Finder window is open, an error sound plays every time. I therefore need to code the script to check if there are any open Finder windows, and if this is the case, to then close them. Here is the code I have so far:

tell application "Finder" to activate
tell application "System Events"
    keystroke "w" using {command down, option down}
end tell

Just missing the "if open Finder windows then" part at the beginning. Could someone help me for this line of code?

1

You can use the following AppleScript code to avoid an error if Finder doesn't have any windows open.


tell application "Finder"
    activate
    if exists window 1 then
        tell application "System Events"
            keystroke "w" using {command down, option down}
        end tell
    end if
end tell
1

If you're just looking for a command to close Finder windows, that will not produce a system sound if no windows are open... Wouldn't it be more efficient to just use this one line of AppleScript code without the need to activate Finder or involve System Events?

tell application "Finder" to close windows

On my end, running that line of AppleScript code while having no Finder windows open, did not produce any error or system sound.

This works for me using the latest version of macOS Mojave.

  • 1
    This is the correct answer, OP should not be sending keyboard events to a scriptable application in place of Scriptable Commands that are in that apps dictionary. In general, if you are sending keystrokes or manipulating the mouse in Applescript, then you are probably doing it wrong, that is not how Applescript was intended to work. – Glen Yates Mar 15 at 16:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .