Wot he said!

By default, Mach3 provides the button but doesn't have the code behind it. This is usually machine-dependent so there isn't a guaranteed one-size-fits-all piece of code. I suspect that most of the samples that you find on the net are variations are developments of the original and often get tweaked to suit individual requirements.

Phill05 has given you the method of linking the code to the button; your code looks fine but has a few additional checks in it and either would work.