Did some searches here & on the ‘net and haven’t found a good answer yet. What I’m trying to do is call a button twice within the same class in C#.
Here’s my scenario –
I have a form with a button that says “Go”. When I click it the 1st time, it runs through some ‘for’ loops (non-stop) to display a color range. At the same time I set the button1.Text properties to “Stop”. I would like to be able to click the button a 2nd time and when that happens I would like the program to stop. Basically a stop-and-go button. I know how to do it with 2 button events, but would like to utilize 1 button.
Right now the only way to end the program is the X button on the form.
I’ve tried different things and haven’t had much luck so far so wanted to ask the gurus here how to do it.
BTW, this is a modification of a Head First Labs C# book exercise.
Thanks!
~Allen
You would need to use Multithreading (launch the process intensive code asynchronously in a separate thread), for instance, using the
BackgroundWorkerobject in .NET 2+. This would be necessary because your UI will not respond to the user’s click until the loop running in the Start method is completed. It is quite irrelevant if you use the same button or another one to toggle the process, because the processor is busy processing the loop.The
BackgroundWorkerhas a property calledWorkerSupportsCancellationwhich needs to be true in this scenario. When the user clicks Stop you would invoke theCancelAsyncmethod of theBackgroundWorker.See MSDN for a good example. Also DreamInCode has a good tutorial which seems quite similar to your requirement.