在使用c#做WinFrom开发时,经常会用到进度条(ProgressBar)。那么如何才能实现winfrom进度条及进度信息提示呢?
方法一:多线程
使用c#做WinFrom开发,要实现进度条效果就需要用到多线程,如果不采用多线程控制进度条,窗口很容易假死(无法适时看到进度信息) | |
---|---|
1、设计界面
需要引用 using System.Threading;
控件名称分别为:progressBar1;label1;textBox1;button1;
2、定义一个代理
代理用于更新ProgressBar的值(Value)及在执行方法的时候,返回方法的处理信息。
private delegate void SetPos(int ipos,string vinfo);//代理
3、设置进度条更新函数
进度条值更新函数(参数必须跟声明的代理参数一样)
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);
}
}
4、函数实现
private void button1_Click(object sender, EventArgs e){
Thread fThread = new Thread(new ThreadStart(SleepT));
fThread.Start();
}
5、新的线程执行函数:
private void SleepT(){
for (int i = 0; i < 500; i++){
System.Threading.Thread.Sleep(10);
SetTextMesssage(100*i/500,i.ToString()+“\r\n”);
}
}
程序运行效果图:
方法二:通过控件backgroundWorker1实现
1、主窗体设计:
控件名称:button1;backgroundWorker1;
对backgroundWorker1控件,属性设置:
2、主页面后台代码:
using System.Threading;//引用空间名称
private void button1_Click(object sender, EventArgs e){
this.backgroundWorker1.RunWorkerAsync(); // 运行 backgroundWorker 组件
ProcessForm form = new ProcessForm(this.backgroundWorker1);// 显示进度条窗体
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{
}
}
//你可以在这个方法内,实现你的调用,方法等。
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){ // 如果用户取消则跳出处理数据代码
e.Cancel = true;
break;
}
}
}
分别为button控件和backgroundWorker1控件选好事件。
3、设置子窗体(及显示进度条的窗体):
控件名称:progressBar1;button1
4、子窗体
后台代码:
private BackgroundWorker backgroundWorker1; //ProcessForm 窗体事件(进度条窗体)
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();//执行完之后,直接关闭页面
}
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选好事件
执行效果为: