stop a macro when pressing the Esc key

I need help for de macro!

Is there any way to stop a macro when pressing the Esc key?

or event (class) that can detect the use of ESC keys?

I looked everywhere and I found no solution, will anyone have any idea how I can do it?

thank.

SolidworksApi/macros
Answers 4
PB
PB 2021-03-26 Best Answer

If your macro is stuck in some endless loop, press Ctrl + Pause Break. I read that escape might also work, but I don't remember that working.

If you really want to stop on a keypress, you need an Event to catch key presses and filter out the escape key. Then, every now and then in your code, you should check if you have already received a keypress.

There are probably better, proper ways to do this though. What is the real problem you are trying to solve?

MN
MN 2021-03-26

Thanks for help.

PB
PB 2021-03-26

You can also show a form while the macro is running with a cancel button. If you show the form non-modal and call DoEvents every now and then, the UI does not freeze and can register the button click.

You can search the SW help for event examples in VBA. It's a bit tricky but very doable. Also check the VBA help: 

KeyPress event | Microsoft Docs 

MN
MN 2021-03-26

Hi, Thanks for your response

I was wondering how to make an event to capture if the Esc key was pressed.
I want to be able to cancel a macro when it is running, and if it is doing something it shouldn't be or taking too long.