5

Possible Duplicate:
Winforms Progress bar Does Not Update (C#)

First time asking a question here for me.

I'll try to explain my problem using this code snippet:

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 pops up at the time the for loop is finished, not when the progressbar has finished drawing. Is there any way to wait until the progressbar has finished drawing before continuing?

Thanks guys!

4

3 回答 3

4

你可能想看看System.Windows.Forms.Application.DoEvents()参考

progressBar1.Maximum = 50;
for (int i = 0; i < 50; i++)
{
    progressBar1.Value++;
    Application.DoEvents();
}
MessageBox.Show("Finished");
progressBar1.Value = 0;
于 2011-08-23T11:49:17.667 回答
2

这里的问题是您正在 UI 线程上完成所有工作。为了重新绘制 UI,您通常需要泵送 Windows 消息。解决此问题的最简单方法是告诉进度条进行更新。调用Control.Update将强制同步完成任何挂起的绘图。

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

其他可行的方法是使用后台线程(使用所有额外的 Control.Invoke 调用来同步回 UI 线程)。DoEvents(如前所述)也应该工作 - DoEvents 将允许您的窗口再次处理消息一段时间,这可能允许您的绘制消息通过。但是,它将泵送消息队列中的所有消息,因此可能会导致不必要的副作用。

于 2011-08-23T13:03:32.433 回答
1

试试下面的代码

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

progressBar1.Value = 0;
于 2011-08-23T11:50:48.803 回答