我想在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