在我們使用c#做WinFrom開(kāi)發(fā)時(shí),經(jīng)常會(huì)用到進(jìn)度條(ProgressBar)。那么如何才能實(shí)現(xiàn)winfrom進(jìn)度條及進(jìn)度信息提示呢?
使用c#做WinFrom開(kāi)發(fā),要實(shí)現(xiàn)進(jìn)度條效果就需要用到多線程,如果不采用多線程控制進(jìn)度條,窗口很容易假死(無(wú)法適時(shí)看到進(jìn)度信息)。
需要引用 using System.Threading;
控件名稱分別為:progressBar1;label1;textBox1;button1;
代理用于更新ProgressBar的值(Value)及在執(zhí)行方法的時(shí)候,返回方法的處理信息。
private delegate void SetPos(int ipos,string vinfo);//代理
進(jìn)度條值更新函數(shù)(參數(shù)必須跟聲明的代理參數(shù)一樣)
private void SetTextMesssage(int ipos,string vinfo){
if (this.InvokeRequired){
SetPos setpos = new SetPos(SetTextMesssage);
this.Invoke(setpos, new object[] { ipos,vinfo });
}
else{
this.label1.Text = ipos.ToString() + "/1000";
this.progressBar1.Value = Convert.ToInt32(ipos);
this.textBox1.AppendText(vinfo);
}
}
private void button1_Click(object sender, EventArgs e){
Thread fThread = new Thread(new ThreadStart(SleepT));
fThread.Start();
}
private void SleepT(){
for (int i = 0; i < 500; i++){
System.Threading.Thread.Sleep(10);
SetTextMesssage(100*i/500,i.ToString()+"\r\n");
}
}
程序運(yùn)行效果圖:
控件名稱:button1;backgroundWorker1;
對(duì)backgroundWorker1控件,屬性設(shè)置:
using System.Threading;//引用空間名稱
private void button1_Click(object sender, EventArgs e){
this.backgroundWorker1.RunWorkerAsync(); // 運(yùn)行 backgroundWorker 組件
ProcessForm form = new ProcessForm(this.backgroundWorker1);// 顯示進(jìn)度條窗體
form.ShowDialog(this);
form.Close();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){
if (e.Error != null){
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled){
}
else{
}
}
//你可以在這個(gè)方法內(nèi),實(shí)現(xiàn)你的調(diào)用,方法等。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i < 100; i++){
Thread.Sleep(100);
worker.ReportProgress(i);
if (worker.CancellationPending){ // 如果用戶取消則跳出處理數(shù)據(jù)代碼
e.Cancel = true;
break;
}
}
}
分別為button控件和backgroundWorker1控件選好事件。
控件名稱:progressBar1;button1
后臺(tái)代碼:
private BackgroundWorker backgroundWorker1; //ProcessForm 窗體事件(進(jìn)度條窗體)
public ProcessForm(BackgroundWorker backgroundWorker1){
InitializeComponent();
this.backgroundWorker1 = backgroundWorker1;
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){
//this.Close();//執(zhí)行完之后,直接關(guān)閉頁(yè)面
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){
this.progressBar1.Value = e.ProgressPercentage;
}
private void button1_Click(object sender, EventArgs e){
this.backgroundWorker1.CancelAsync();
this.button1.Enabled = false;
this.Close();
}
只為button選好事件
執(zhí)行效果為:
以上就是C#實(shí)現(xiàn)winfrom進(jìn)度條及進(jìn)度信息提示的方法介紹,希望對(duì)大家有所幫助。
更多建議: