我想在ProgressBar
上显示文字,(没有所有的废话都是custom progress bar)。这不难做到,并且不涉及OnPaint
方法 - 如以下代码的button1所示。但是,此方法会阻止UI线程,即evil。 不幸的是,我最擅长的一种异步方法会导致文本闪烁,这非常烦人。为什么我的异步ProgressBar闪烁的文本?
有人可以告诉我如何在没有闪烁的情况下异步更新文本吗?
(要运行下面的代码,只需将其粘贴到包含的三个键和3个ProgressBars一个形成一个新的项目 )。
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
namespace ProgBarTest //change namespace in Program.cs accordingly
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//This method will block the main UI thread
// (thus freezing the other buttons)
StartUpdate(this.progressBar1);
}
private void button2_Click(object sender, EventArgs e)
{
//this method (and the next) don't block the UI, and can be used concurrently,
// but the text flickers
Task t = new Task(() => StartUpdate(this.progressBar2));
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
Task t = new Task(() => StartUpdate(this.progressBar3));
t.Start();
}
private void StartUpdate(ProgressBar progBar)
{
for (int i = 1; i <= 100; i++)
{
UpdateProgressBar(i, progBar);
Thread.Sleep(100);
}
}
private void UpdateProgressBar(int i, ProgressBar progBar)
{
if (progBar.InvokeRequired) //for use with background Task
{
progBar.Invoke(new Action<int, ProgressBar>(UpdateProgressBar),
new Object[] { i, progBar });
}
else
{
//set progress bar:
progBar.Value = i;
progBar.Refresh();
//set status label:
string percentStr = i.ToString() + "%";
PointF location = new PointF(progBar.Width/2 - 10, progBar.Height/2 - 7);
using (Graphics gr = progBar.CreateGraphics())
{
gr.DrawString(percentStr, new Font("Arial",10), Brushes.Red, location);
}
}
}
}
}
谢谢。这是我的第一个策略,但我希望文本放置在ProgressBar的顶部,并且我无法找到将progresLbl设置为透明背景。 – kmote
好吧,那么也许你可以尝试一些基于这个问题的答案(如果你还不想创建自定义ProgressBar):http://stackoverflow.com/q/10714358/2931053 – Pricey