2014-12-05 117 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();