使用ProgressBar,並且通過數字的形式顯示進度,一開始以為很簡單啊(其實是真的很簡單),於是乎一開始的代碼是這樣的:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
for (int i = 0; i < 100; i++)
{
this.Text = i.ToString();
this.progressBar1.Value = i;
Thread.Sleep(100);
}
}
}
毫無疑問,GG不能顯示進度的數字,不過進度條還是跑的很歡快的啊。這樣可不是我要的效果啊。求助!於是找到了這個鏈接,Here
代碼上:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.FixedSingle;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// 獲取異步任務進行的百分比
progressBar1.Value = e.ProgressPercentage;
this.label1.Text = e.ProgressPercentage.ToString();
}
}
注解:backgroundWorker1 是一個可以開啟后台任務的組件,這里要設置這個控件的 WorkerRepoertsProcess 屬性為 True 這樣我們才能在 ProcessChange 事件中接收到 ProgressPercentage
最后的效果圖:
這只是一個簡單的demo,做一個記錄!