Put your code in Form_QueryUnload event.
Yes, use the QueryUnload event if you want to have the option of cancelling (stopping) the unload. You can also place code in the Unload event (which fires
after QueryUnload), but at that point you don't have the option to cancel the close.
One nice thing about QueryUnload is that you receive a parameter telling you how/why the close was requested. So you can react differently depending on whether the user closed the form, or your code did it, or Windows is shutting down.