C #: Wait for the drawing to finish

Possible duplicate:
Winforms progress bar not updating (C #)

First asked a question for me.

I will try to explain my problem using this piece of code:

progressBar1.Maximum = 50; for (int i = 0; i < 50; i++) { progressBar1.Value++; } MessageBox.Show("Finished"); progressBar1.Value = 0; 

The problem with this code is that the MessageBox appears during the completion of the for loop, not when the progress bar has finished drawing. Is there a way to wait for the progress bar to finish drawing before continuing?

Thanks guys!

+4
source share
3 answers

You might want to look at System.Windows.Forms.Application.DoEvents() . Link

 progressBar1.Maximum = 50; for (int i = 0; i < 50; i++) { progressBar1.Value++; Application.DoEvents(); } MessageBox.Show("Finished"); progressBar1.Value = 0; 
+3
source

The problem is that you are doing all your work on the user interface thread. To re-draw the user interface, you will typically need to download Windows messages. The easiest way to fix this is to specify a progress bar for the update. Calling Control.Update will cause any pending drawing to execute synchronously.

 progressBar1.Maximum = 50; for (int i = 0; i < 50; i++) { progressBar1.Value++; progressBar1.Update(); } MessageBox.Show("Finished"); progressBar1.Value = 0; 

Other methods that may work are to use a background thread (with all the additional Control.Invoke calls necessary to synchronize with the user interface thread). DoEvents (as mentioned earlier) should also work - DoEvents will allow your window to process messages again for a time that may allow your paint messages. However, it will pump all the messages in the message queue so that it can cause unwanted side effects.

+1
source

Try using the following code

 progressBar1.Maximum = 50; for (int i = 0; i < 50; i++) { this.SuspendLayout(); progressBar1.Value++; this.ResumeLayout(); } MessageBox.Show("Finished"); progressBar1.Value = 0; 
0
source

All Articles