March 27, 2014

Why doesn’t SHIFT-ESC stop my compiled macros?

Filed under: Automation,Scripting — Marcus Tettmar @ 9:59 am

You might find that when you run a compiled macro and you also have Macro Scheduler running, Shift-Esc – the default stop key sequence – doesn’t stop the compiled macro.

This is because the stop key sequence is a system wide hot key. And system wide hot keys can only be registered for use by one application at a time. So if Macro Scheduler is already running when you start your .exe the .exe is unable to register Shift-Esc because Macro Scheduler already has it.

Of course when you deploy your .exe to people who don’t already have Macro Scheduler – which is usually the case – there won’t be any problem because Macro Scheduler won’t be running and so your .exe is able to register the Shift-Esc hot key.

But what if you want to define your own stop hot key, or you want to give your users the option of setting it? Well what you need is a KEY_DOWN event handler:

//CTRL-Z is stop key
OnEvent>KEY_DOWN,VK90,2,doExit
Let>paused=FALSE

//sample code here ...
Wait>20
MessageModal>hello

SRT>doExit
   Exit>0
END>doExit

Here we have set up a key down event handler for CTRL+Z. VK90 is Z and 2 is the modifier key for CTRL. See the OnEvent help topic and Virtual Key Codes List.

The event handler basically sets up a concurrent thread that is running all the while the main script is running. This allows it to respond to events such as this KEY_DOWN event. So when you hit the specified key sequence – in this case CTRL+Z, the doExit subroutine runs and all that does is call the Exit function which terminates the script.

You could be smarter and ask the user if he really means he wants to exit:

SRT>doExit
   Ask>Are you sure you want to exit?,ynExit
   If>ynExit=YES
      Exit>0
   Endif
END>doExit

When you compile the macro there is an option to disable the standard Shift-Esc sequence. So you could do that to completely replace the stop key system with your own custom one using your OnEvent.

Consider an INI file and possibly another config script using a custom dialog to allow the user to set his own stop key sequence. Other apps could already be using it. My CTRL+Z example is probably not ideal as although it is used in Linux to suspend the current process it is usually the short cut for Undo in Windows.