如何在progressBar中显示绿色进度以及内部百分比?

时间:2014-12-05 08:08:08

标签: c# .net winforms

我有这段代码:

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)));
    }
}

仍然在progressBar中的百分比一遍又一遍地涂抹。

我使用的toolStripProgressBar2包含progressBar

2 个答案:

答案 0 :(得分:0)

gr.DrawString(percent.ToString() + "%",SystemFonts.DefaultFont,Brushes.Black,...

请检查以下链接。您需要使用DrawString的重载来添加画笔

http://www.dreamincode.net/forums/topic/94631-add-the-percent-into-a-progress-bar-updated/

答案 1 :(得分:-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();