Why AppleScript always send keystrokes with Comman

2020-06-23 05:53发布

I see a lot of examples of AppleScript like this

tell application "TextEdit"
    activate
    tell application "System Events"
        keystroke "s"
    end tell
end tell

Expected result is that letter "s" will be typed into active document in TextEdit (assume there is at least one document window). But instead it always tries to save document (did it for changed document and open save dialog if it is a new). Same things happen for any key in any application at any time…

Does anybody know why System Events always send keystrokes like "… using {command down}"?

标签: applescript
4条回答
Animai°情兽
2楼-- · 2020-06-23 06:18

I run script from AppleScript Editor using Cmd+R, not by clicking Run button. Script begins executing immediately after I press key "R" down and that script sends keystroke "S" before I release Cmd or R. That's why sent keystroke "S" interprets by TextEdit with modifier Cmd.

The workaround is to click button Run or add delay at the beginning of script and use Cmd+R:

delay 0.2 -- 0.2 second delay is enough

tell application "TextEdit"
    activate
查看更多
看我几分像从前
3楼-- · 2020-06-23 06:21

How are you executing the script? If you're doing so with a keyboard shortcut involving the Command key, then you're holding down the key, not the script.

查看更多
家丑人穷心不美
4楼-- · 2020-06-23 06:25

Are you sure? Using the exact code you posted, it typed the letter s in TextEdit. You'll still have to use key down {command} or key up {command} for it to do a save (⌘ Command S).
Also, if you hold the ⌘ Command key down when executing, the command entered in TextEdit, would be ⌘ Command S.

You may want to look at this article on WikiBooks, which should help you understand it better.

查看更多
成全新的幸福
5楼-- · 2020-06-23 06:33

Even better to check for it, and apply the delay only if necessary, and as long as necessary. (~Busy wait till user does cmd up. I even used some disturbing sound to facilitate it, so the script in fact does cmd up in a way. :D)

And also especially notice that this way the key sequence cannot turn into commands, because it won't fire while the cmd is down.

on check()
    do shell script "~/Documents/checkModifierKeys cmd" --DOWNLOAD: http://macscripter.net/viewtopic.php?pid=114479#p114479
end check

on run {input, parameters}
    set the date_stamp to do shell script "date '+%Y.%m.%d_%H:%M'"
    repeat while check() = "1"
        beep
        delay 0.2
    end repeat
    tell application "System Events"
        tell process "TextEdit" to keystroke date_stamp
    end tell

    return input
end run

Notice: I used a tool I'd downloaded. I also found references of utilities OsX should have, but no luck on Lion. But the downloaded one works for sure.

查看更多
登录 后发表回答