开发者

Why AppleScript always send keystrokes with Command down?

开发者 https://www.devze.com 2023-03-17 04:46 出处:网络
I see a lot of examples of AppleScript like this tell application \"TextEdit\" activate tell application \"System Events\"

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 do开发者_如何学编程cument 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}"?


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消