2014-12-05 118 views
-1

我有这样的代码:如何显示progressBar中的绿色进度和百分比?

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    this.toolStripProgressBar2.Value = Math.Min(this.toolStripProgressBar2.Maximum, e.ProgressPercentage); 
    this.toolStripProgressBar2.ProgressBar.CreateGraphics().DrawString(e.ProgressPercentage.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(this.toolStripProgressBar2.Width/2 - 10, this.toolStripProgressBar2.Height/2 - 7)); 
} 

,如果我只用第二行则显示百分比,但没有绿色进度。 如果我也使用第一行,则每次绿色进度时将删除百分比。

。如果我只用第二行中的百分比看起来他们画一遍又一遍地对他们的自我:

Percentages only

,如果我只使用第一行只有我会看到绿条进展良好,但没有百分比。

这就是我现在尝试:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    using (Graphics gr = this.toolStripProgressBar2.ProgressBar.CreateGraphics()) 
    { 
     gr.DrawString(e.ProgressPercentage.ToString() + "%", 
      SystemFonts.DefaultFont, 
      Brushes.Black, 
      new PointF(this.toolStripProgressBar2.ProgressBar.Width/2 - (gr.MeasureString(e.ProgressPercentage.ToString() + "%", 
       SystemFonts.DefaultFont).Width/2.0F), 
      this.toolStripProgressBar2.ProgressBar.Height/2 - (gr.MeasureString(e.ProgressPercentage.ToString() + "%", 
       SystemFonts.DefaultFont).Height/2.0F))); 
    } 
} 

而且还是在进度百分比自己是画一遍又一遍就可以了。

我使用toolStripProgressBar2包含progressBar

+1

这是非常非常错误代码。你应该处置你自己创建的'Graphics'实例。 – 2014-12-05 08:15:18

回答

-1

这听起来一个UI线程被阻塞其他。另外我建议你检查Progressbar Perform Ste。而就Microsoft

progressBar.PerformStep(); 

它迫使进度更新进度每个实例

toolStripProgressBar2.Value = Math.Min(this.toolStripProgressBar2.Maximum,e.ProgressPercentage); 


toolStripProgressBar2.ProgressBar.CreateGraphics().DrawString(e.ProgressPercentage.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(this.toolStripProgressBar2.Width/2 - 10, this.toolStripProgressBar2.Height/2 - 7)); 
toolStripProgressBar2.PerformStep();