There are various problems that you will have to face when you hang a user interface thread like this. This, of course, is one of them, nothing pleasant happens when the user wildly knocks on a button to try to achieve something noticeable. And of course, these clicks will not be lost, they will remain stored in the message queue. To activate the Click event handler again when the event handler stops working.
It is important to learn how to use the BackgroundWorker or Task classes to avoid such troubles. Just for this, just set the Enabled property.
Clearing mouse clicks from the message queue is technically possible. But ugly to do, it requires pinvoke. I hesitantly publish an alternative, do not think that this is generally a good strategy. You will need to read this post to get an idea of โโwhy DoEvents () is a dangerous method.
private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; button1.Update(); '' long running code ''... Application.DoEvents(); if (!button1.IsDisposed) button1.Enabled = true; }
Calling Update () ensures that the user receives feedback that he needs to know that repeatedly pressing the button will not bring anything useful. In the DoEvents () call, all mouse clicks in the queue will be sent, nothing happens to them, since the button is still disabled. The IsDisposed test is necessary to solve the problem with DoEvents (), this ensures that your program does not work when the user clicks the Close button while the code is running.
Use the HourGlass class in this post to provide more feedback.
source share