在執行耗時較長的任務時,增加一個進度條顯示任務的進度,能夠給用戶一個很好的體驗,如果沒有進度條顯示進度,用戶會誤以為程序運行出錯或死機了。那么在C#winform窗體應用程序中如何設計一個進度條呢,以下以一個簡單的demo說明過程。下面這個demo主要由三部分組成:主窗體、進度顯示窗體、執行任務的C#類。先來設計主窗體,主窗體只設置一個按鈕。注意:網上某些文章還在主窗體里設置了BackgroundWorker控件,我不建議直接使用BackgroundWorker控件,因為使用這個控件后,如果執行任務過程中臨時取消任務,然后再次想要重啟任務時會出現錯誤“此 BackgroundWorker 當前正忙,無法同時運行多個任務”。這是因為使用控件時,BackgroundWorker對象成為一個固定的對象。在本demo中,直接在主窗體的按鈕點擊事件中用new方法創建BackgroundWorker對象,每次點擊按鈕都產生不同的BackgroundWorker對象。using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public BackgroundWorker worker;
private void button1_Click(object sender, EventArgs e)
{
//創建一個Backgroundworker,設置其參數
this.worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(backgroundwork); //執行工作時,綁定對應的方法
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); //工作完成時,綁定對應的方法
worker.WorkerReportsProgress=true; //允許報告進度
worker.WorkerSupportsCancellation=true; //支持中途取消
//開始執行操作
worker.RunWorkerAsync();
ProcessForm form = new ProcessForm(worker);// 顯示進度條窗體
form.ShowDialog(this);
form.Close();
}
private void backgroundwork(object sender, DoWorkEventArgs e)
{
DataOperate dataOperate = new DataOperate(); //執行實際任務的類
dataOperate.operating(worker); //傳入worker,以便于報告進度
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
this.worker.CancelAsync();
}
else
{
}
}
}
}
進度條顯示窗體,由一個processbar控件和一個按鈕組成,界面如下:using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public partial class ProcessForm : Form
{
private BackgroundWorker backgroundWorker1;
public ProcessForm(BackgroundWorker backgroundWorker1)
{
InitializeComponent();
this.backgroundWorker1 = backgroundWorker1;
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessForm_Load(object sender, EventArgs e)
{
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();//執行完之后,直接關閉頁面
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void button1_Click_1(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
this.button1.Enabled = false;
this.Close();
}
}
}
最后,是執行耗時任務的類DataOperate.cs,這里模擬了一個耗時10秒的任務,全部代碼如下:using System.ComponentModel;
using System.Threading;
namespace Test
{
internal class DataOperate
{
public void operating(BackgroundWorker worker)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
worker.ReportProgress(i*100/10);
}
}
}
}
程序運行后,點擊“開始”按鈕,就會彈出進度條顯示進度,點擊“取消”可取消任務,取消任務后可再次點擊“開始”再次執行任務。
閱讀原文:原文鏈接
該文章在 2025/1/7 11:42:10 編輯過