I use a bit of UI scripting to automate some of the screenshots used in Marked marketing and documentation. One (significant) part of that scripting is sending keyboard commands, so I’ve built a few routines to help out.
The script includes 3 different routines. The base is keyCmd(_string). It takes a single key, with modifiers either typed out or defined using DefaultKeyBindings-style shortcuts, where “$” is Shift, “~” is Option, “^” is Ctrl, and “@” is Command. So you can send either “cmd i” or “@i”. Named keys are recognized, so you can also use “shift opt left” to hit ⇧⌥←. When using named keys, you need to either have a space after shortcuts (e.g. “$~ left”), or use the string versions, as in the previous example.
keySeq is a shortcut for sending a batch of keyCmds at once, e.g. keySeq("@n $~@s",1) to send Command-N followed by Shift-Option-Command-S. The second parameter is the delay between keys, 0 for none.
keyType takes a string and a delay and types each character out, simulating keyboard typing. This command doesn’t allow modifiers, just characters, and the modifier shortcuts are typed as characters. Running keyType("This will type out in whatever field is focused",.01) will simulate typing the sentence out with a very brief delay between each keystroke.
I’m just sharing these in case they’re of use in your own scripting. If I get around to it, I’ll share more of my routines for window manipulation, menu clicking, and screen capture. I’m certain I can name several readers who will know of more elegant ways to accomplish all of these. I’d be delighted to update with your genius if you share it.