Is it possible to automate holding down a button for X time?

ok thanks I thought that might be the case. So I guess what I need isnt the 'while' action at all?

Is it possible to automate holding down the button for a certain amount of time and run actions while the key is down? And then of course releasing the button after x seconds?

Yes I would love to know the answer as well.

This was probably never seen because it was posted in a topic entitled ā€œUnderstanding the ā€˜Whileā€™ actionā€

It is always best to ask a new question in a new topic unless it is strongly related to the originating topic.

You can hold a mouse button down using the Move or Click Mouse action with the ā€œand holdā€ option at the bottom. The button will stay held until the macro completes or until a corresponding click action releases it.

Roger that. I have moved this conversation to a new topic.

Yes, it is possible, I'm aware that you can do it with AppleScript.

tell application "System Events"
   key down {command}
   key down "a"
   tell application "Keyboard Maestro Engine"
      do script "%Script Name or KM Macro Name%"
   end tell
   key up {command}
   key up "a"
end tell

The above is an example of holding down CMD + A. You can either put the desired macro in between the "down" and "up", but if you need a literal amount of time, you can do a "delay command"
ex.

 delay 3

^^^ delays for three seconds

Hey Michael,

As written that's potentially dangerous.

If an error is thrown before the key-up events you're seriously stuck until you restart your system.

Here's how I'd write that to mitigate the danger:

tell application "System Events"
   
   try
      
      key down {command}
      key down "a"
      
      tell application "Keyboard Maestro Engine"
         do script "%Script Name or KM Macro Name%"
      end tell
      
      key up {command}
      key up "a"
      
   on error e number n
      
      key up {command}
      key up "a"
      
      set e to e & return & return & "Num: " & n
      if n ā‰  -128 then
         try
            tell application (path to frontmost application as text) to set ddButton to button returned of Ā¬
               (display dialog e with title "ERROR!" buttons {"Copy Error Message", "Cancel", "OK"} Ā¬
                  default button "OK" giving up after 30)
            if ddButton = "Copy Error Message" then set the clipboard to e
         end try
      end if
   end try
   
end tell

-Chris

1 Like

Didn't know that could happen! Thanks for that. Adding it to my macro.

Which is why Keyboard Maestro releases all keys and modifiers that are held down by a macro when the macro ends.

1 Like