进度条值只是闪烁并消失

时间:2013-07-08 11:30:24

标签: c# winforms

我正在尝试将百分比值放入我的进度条,但它看起来像一个闪烁然后消失。

这是我的ProgressChanged事件:

C#代码

public void button1_click(object sender, EventArgs e)
{
BackgroundWorker _worker = new BackgroundWorker();
                _worker.WorkerReportsProgress = true;
                _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);
                _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);                
                _worker.DoWork += (s, e2) =>
                {
                    for (int i = 0; i <= xmlnode.Count - 1; i++)
                    {
                         _worker.ReportProgress((int)100 * i / (xmlnode.Count - 1));
                         // Many validations here
                    }
                 }
}

void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
            progressBar1.Value = e.ProgressPercentage;            

             // Here I tryied to put the percentage value in progress bar

            int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
            progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }

2 个答案:

答案 0 :(得分:0)

文字只是闪烁,因为它没有在Paint上重新绘制。使用进度条的Paint事件并在那里绘制百分比。只需将其存储在类变量中即可轻松获取该百分比。

答案 1 :(得分:0)

进度条是一个动画控件。当您更改其百分比时,它会使其绘图表面无效并完全重绘它。这意味着您为一帧绘制了百分比,然后在动画滚动时消失。

要解决此问题,您必须创建一个继承自Control或Progress bar的新控件,并将您的代码添加到处理百分比写入的OnPaint事件中。通过在OnPaint中,每次控件重新绘制自己时都会执行它,而不仅仅是一次。或者,只需将委托挂钩到现有进度条的现有Paint事件,这可能更容易。

这看起来像是:

//Somewhere during initialisation, this is called once only
progressBar1.Paint+= new PaintEventHandler((object sender, PaintEventArgs e) => 
e.Graphics.DrawString(progressBar1.Value.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7)));