The fact that you're using Application.DoEvents
is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have little choice - but that suggests you should simplify your UI... and it's not applicable in this case, I suspect.)
Instead, you should be performing the long-running task (creating the files) in a separate thread. BackgroundWorker is a perfect fit for this - you can use it to report progress back to the UI, and the UI can call CancelAsync
method to request that it stops. You need to check the CancellationPending
property from within the worker thread, to see whether cancellation has been requested, and stop appropriately.
EDIT: Just to clarify what I believe is happening - I suspect your form is closing, but the program won't terminate until the event loop has finished. You're keeping the event loop going with your file-creation loop, hence the problem.
Note that there isn't a thread for the button - there's just one for your whole UI. (In certain cases you may need more than one UI thread, but that's rare - and you'd know it if you'd done it.)