I’ve got a WinForm, which contains a button. In the button’s click event, I call button1.Enabled = false and then a number of lines of code follow. After this code, I call button1.Enabled = true.
This is done so that the button cannot be pressed while the execution is being carried out. The strange thing is that while the button is disabled, if the user clicks on the button many times, the button is actually clicked.
Could anyone explain why this is happening? The code looks like this:
button1.Enabled = false
//Code
//Code
//Code
button1.Enabled = true
My guess is that you’re actually doing a load of work in those lines of code, blocking the UI thread. You shouldn’t do that – you should set the button to be disabled, then start off your work in a background thread (or using asynchronous calls, if most of the time is spent talking to a web service or something similar). Then when the work is finished, it should marshal a call back into the UI thread to re-enable the button.
(If that’s not the problem, please show a short but complete program which demonstrates the problem.)
EDIT: Thanks to Sarwar’s comments, I understand why you’re getting the multiple events being fired – they’re being queued up (due to the UI thread being blocked), and only processed after the button is re-enabled. So yes, if you avoid doing lots of work on the UI thread, it can handle the clicks on the disabled button, ignore them, and then there won’t be a backlog when the button is re-enabled.
EDIT: For anyone who is interested in trying this themselves, here’s my test program demonstrating the problem:
And the fix using C# 5’s async handling: