在我们使用c#做WinFrom开发时,经常会用到进度条(ProgressBar)。那么如何才能实现winfrom进度条及进度信息提示呢?
C#多线程教程
使用c#做WinFrom开发,要实现进度条效果就需要用到多线程,如果不采用多线程控制进度条,窗口很容易假死(无法适时看到进度信息)。
需要引用 using System.Threading;
控件名称分别为:progressBar1;label1;textBox1;button1;
代理用于更新ProgressBar的值(Value)及在执行方法的时候,返回方法的处理信息。
private delegate void SetPos(int ipos,string vinfo);//代理
进度条值更新函数(参数必须跟声明的代理参数一样)
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");
}
}
程序运行效果图:
控件名称:button1;backgroundWorker1;
对backgroundWorker1控件,属性设置:
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控件选好事件。
控件名称:progressBar1;button1
后台代码:
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选好事件
执行效果为:
以上就是C#实现winfrom进度条及进度信息提示的方法介绍,希望对大家有所帮助。