c#中进度条上的文字

时间:2011-11-24 15:08:25

标签: c# progress-bar winapp

我正在使用以下代码。

为什么它运行不正常?

private void Form1_Shown(object sender, EventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        Application.DoEvents();
        Thread.Sleep(200);

        progressBar1.Refresh();
        progressBar1.Value = i;
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%",
            new Font("Arial", (float)8.25, FontStyle.Regular),
            Brushes.Black, new PointF(progressBar1.Width / 2 - 10,
                progressBar1.Height / 2 - 7));


    }
}

更新:

为什么不总是显示文字?

2 个答案:

答案 0 :(得分:1)

这有效 - 尽管我将线程睡眠设置为超过200毫秒。你的问题是你在UI线程中完成了工作,这种方式永远不会得到更新。为了获得更好的可见性,只需更改字体颜色:

 private void Form1_Load(object sender, EventArgs e)
{
  Task t = new Task(() => StartUpdate());
  t.Start();

  t.ContinueWith(task => Console.WriteLine("Done loading"));
}

 private void StartUpdate()
{
  for (int i = 1; i <= 100; i++)
  {
    UpdateProgressBar(i);
  }
}

private void UpdateProgressBar(int i)
{
  if (progressBar1.InvokeRequired)
  {
    progressBar1.Invoke(new Action<int>(UpdateProgressBar), new Object[] { i });
  }
  else
  {
    Thread.Sleep(200);
    progressBar1.Refresh();
    progressBar1.Value = i;
    progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
                                          (float)10.25, FontStyle.Bold),
                                          Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
  }
} 

答案 1 :(得分:-2)

使用它。有很好的方法可以做到这一点但是因为你的问题是为什么它不起作用,因为它有Application.DoEvents();

    private void Main_Shown(object sender, EventArgs e)
    {
        for (int i = 1; i <= 100; i++)
        {
            progressBar1.Value = i;
            int percent = (int)(((double)(progressBar1.Value -progressBar1.Minimum) / (double)(progressBar1.Maximum - progressBar1.Minimum)) * 100);
            using (Graphics gr = progressBar1.CreateGraphics())
            {
                gr.DrawString(percent.ToString() + "%",  SystemFonts.DefaultFont, Brushes.Black, new PointF(progressBar1.Width / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Width / 2.0F), progressBar1.Height / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Height / 2.0F)));
            }
            System.Threading.Thread.Sleep(200);
        }
    }