private void btnStart_Click(object sender, EventArgs e)
{
pbrProgress.Maximum = 100;//设置最大长度值
this.Cursor = Cursors.WaitCursor;
///添加一个事件处理程序
backgroundWorker1.DoWork += new DoWorkEventHandler(DoWork);
///添加一个显示进度条的事件
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged); //ProgressChanged 是显示进度条Method
///后台已操作完成,关闭窗体
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CloseForm); // CloseForm()调用关闭窗体
///开始执行后台操作
this.backgroundWorker1.RunWorkerAsync(filename);
}
private void DoWork(object sender , DoWorkEventArgs e)
{
e.Result = (WorkTimer(this.backgroundWorker1,e));
}
/// <summary>
/// 设置进度条显示长度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private int WorkTimer(object sender, DoWorkEventArgs e) //此为自己的操作处理函数,切记!!
{
int max = pbrProgress.Maximum;
int percent = 0;
for (int i = 0; i <= max; i++)
{
if (this.backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return -1;
}
else
{
//自己的函数处理计算过程
......
percent = (int)(((double)i / (double)max) * 100);
this.backgroundWorker1.ReportProgress(percent); //单次循环处理完报告进度,触发ProgressChanged事件
}
/// 将当前线程挂起指定的时间
System.Threading.Thread.Sleep(100);
}
return -1;
}
//显示进度条
public void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.pbrProgress.Style = ProgressBarStyle.Continuous;
this.lblMsg.Text=string.Format("已完成{0}%,请稍候...", e.ProgressPercentage);
this.pbrProgress.Value = e.ProgressPercentage;
}
/// <summary>
/// 关闭进度条显示窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void CloseForm(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
一个用backgroundworker实现progressbar的例子(修改版)
最新推荐文章于 2020-11-30 14:52:08 发布