Here is a piece of sample code to demonstrate the problem. I start a BackGroundWorker for the time-cost function DoSomething.
The Button is disabled at first. Then the worker begins to work. Finally, the button is re-enabled after the work has been finished.
BackgroundWorker w = new BackgroundWorker();
/* Disable the button at first */
Button.Enabled = false;
w.WorkerReportsProgress = false;
w.WorkerSupportsCancellation = false;
w.DoWork += new DoWorkEventHandler((s, e) =>
{
DoSomething(); // It may take 10 ms to 10 s
});
w.RunWorkerCompleted += new RunWorkerCompletedEventHandler((s, e) =>
{
/* Enable the button finally */
Button.Enabled = true;
});
w.RunWorkerAsync();
However, the time-cost function DoSomething may returns immediately in some case. Then, Button disable and enable may cause the Button to flicker. It is observed that setting Disable and Enable, forces the Button to be repainted.
Even:
private void AnotherButton_Clicked(object sender, EventArgs e)
{
for (int i = 0; i < 40; i++)
{
Button.Enabled = false;
Button.Enabled = true;
}
}
causes the flicker (please press the button as quickly as possible). Is there a better solution that can reduce the button flicker problem caused by enable and disable?