Use Control.Update()
method, which will make the control to redraw the invalidated regions within its client area.
There are two ways to repaint a form and its contents:
You can use one of the overloads of the Invalidate()
method with the Update()
method.
You can call the Refresh()
method, which forces the control to redraw itself and all its children. This is equivalent to setting the Invalidate()
method to true
and using it with Update()
.
The Invalidate()
method governs what gets painted or repainted. The Update()
method governs when the painting or repainting occurs. If you use the Invalidate()
and Update()
methods together rather than calling Refresh()
, what gets repainted depends on which overload of Invalidate()
you use. The Update()
method just forces the control to be painted immediately, but the Invalidate()
method governs what gets painted when you call the Update()
method.
1)
private void btnPrepare_Click(object sender, EventArgs e)
{
for (int i = 0; i < 8; i++)
{
labels[i].BackColor = System.Drawing.Color.Red;
labels[i].Update();
System.Threading.Thread.Sleep(2000);
}
}
2)
private void btnPrepare_Click(object sender, EventArgs e)
{
for (int i = 0; i < 8; i++)
{
labels[i].BackColor = System.Drawing.Color.Red;
labels[i].Refresh();
System.Threading.Thread.Sleep(2000);
}
}
If you use Application.DoEvents()
method (which is unlikely), it will processes all Windows messages currently in the message queue.
When you run a Windows Form application, it creates the new form, which then waits for events to handle. Each time the form handles an event, it processes all the code associated with that event. All other events wait in the queue. While your code handles the event, your application does not respond. For example, the window does not repaint if another window is dragged on top.
If you call DoEvents()
in your code, your application can handle the other events. In your example, add DoEvents()
to your code, to make your form repaint when another iteration comes. If you remove DoEvents()
from your code, your form will not repaint until the end of the loop.
But, unlike the Refresh()
and Update()
methods, it will process all events (even unnecessary ones).
As a supplement - I would like to add this answer, which briefly (as possible) shows why is DoEvents()
is dangerous for use.