Unreliable working of Applescript System Events commands

Good day to all,

I'm experiencing the awesome combination of KM and applescripts, so in the past weeks i've written over 200 macros to automate my workflow.

In many cases, however, when using System events commands to copy and paste formats, I noticed that sometimes they work, sometimes they don't.

  • tell application "System Events" to keystroke "c" using {command down, option down}

  • tell application "System Events" to keystroke "v" using {command down, option down}

I've tried different delay times, but could find no pattern to explain the erratic behavior.

Any ideas? Thanks

This is one of (many reasons) why you shouldn't try and achieve your goal by way of UI scripting. I'd suggest, where possible, going through each of your scripts/macros and rewriting them using a solution that doesn't involve System Events in this manner.

I experienced the intermittent behaviour you describe using System Events when I switched to Mojave. The solution I found was to quit System Events right before using it for some purpose. When it's quit, it immediately restarts, but seems to work reliably for the remainder of that script. So in your case, an example would be:

tell application "System Events" to quit
tell application "System Events" to keystroke "c" using {command down, option down}

I assumed this is a Mojave bug, but it may help even if you're not using Mojave. I also agree with CJK.

1 Like

Hi @billearl, thanks for the feedback.

I too am using Mojave, and tried the quit line you suggested, but the problem remained.

For the time being, I am using the same command, but invoking the menu item itself, it works all the time.

I would also suggest, like CJK, not working with System events and use KM equivalent action or the clipboard fonction in AS.

An option would be to simulate the keys with Keyboard Maestro. You can use the do script AppleScript command to execute the XML of an action, and you can use the Edit ➤ Copy as XML to copy the XML of the Type a Keystroke actions.

1 Like

thanks Peter, this seems to be a very interesting solution, I see how I could do it with a KM macro, that has the "type keystroke" commands and is called from the Applescript with the "do script" routine, but I'm not quite sure how to implement it with the XML. Can you give me more details?

The XML code goes on the applescript itself? Please forgive me for the newbie kind of questions and thanks again.

Hey Ricardo,

See this for an example:

Keystroke as variable test

-Chris

Hi Chris, thanks,

In the above situation, you've saved the keystroke's XML code as a variable in applescript. That's clear.

But how to get applescritpt to execute that command, that is, to type the actual keys to the targeted app?

tell app "Keyboard Maestro Engine"
    do script "XML GOES HERE"
end tell

Hey Ricardo,

Did you actually download and look at the action?

-Chris