C#中进度栏上的文本 [英] text on progressbar in c#

查看:87
本文介绍了C#中进度栏上的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码.

为什么它不能正常运行?

Why does it not run properly ?

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


    }
}

更新:

为什么不总是显示文本?

推荐答案

这可行-尽管我将线程睡眠设置为200毫秒以上.您的问题是您是在UI线程中完成工作的,因此永远都不会更新.为了获得更好的可见性,只需更改字体颜色:

This works - although I'd set the thread-sleep to more than 200 ms. Your problem was that you did the work in the UI thread and this way it never gets updated. For better visibility, just change the font color:

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

这篇关于C#中进度栏上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆