Search code examples
applescriptkeystroke

Script Editor hiding when telling a different application to close/hide


Why does the following Applescript hide Script Editor?

tell application "Last.fm" to launch
tell application "System Events" to tell process "Last.fm" to keystroke "h" using command down

This code I found will hide "Last.Fm", but also hides Script Editor. Ideally, I want to replace the keystroke "h" with a keystroke "w" but then I get an error:

The document can’t be closed while the script is running.

Why does the script I wrote effect Script Editor?


Solution

  • I don't have Last.fm, so I tried this:

    tell application "TextEdit" to launch
    delay 2
    tell application "System Events" to tell process "TextEdit" to keystroke "h" using command down
    

    And sure enough, it's true, TextEdit was hidden but so was Script Editor.

    Then I tried this:

    tell application "TextEdit" to launch
    tell application "TextEdit" to activate
    delay 2
    tell application "System Events" to tell process "TextEdit" to keystroke "h" using command down
    

    TextEdit was hidden, but Script Editor was not. So I would guess that this will help in your code too. Having the target app frontmost appears to be crucial (which makes a certain amount of sense, after all).