标签:
winform 加载窗体时弹出另一个窗体并显示进度条的源码 //frmA: 源窗体 //------------------------------------------ //引用 using System.Threading; BackgroundWorker worker; public frmA() { InitializeComponent(); worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); } /// <summary> /// 异步 开始事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void worker_DoWork(object sender, DoWorkEventArgs e) { //需要执行的代码 Thread.Sleep(5000); //让进程上卡5秒钟 } /// <summary> /// 事件: 异步执行完成后 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("执行完成。", "run", MessageBoxButtons.OK, MessageBoxIcon.Information); } //点击一个按钮后开始执行 private void btnA_Click(object sender, EventArgs e) { //按钮要执行的代码放在 worker_DoWork 事件中执行 //异步执行开始 worker.RunWorkerAsync(); //显示进度窗体 frmB frm = new frmB(this.worker); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(this); } frmB: //里面放了一个loading.gif图片显示进度 ------------------------------------------------------------ using System; using System.ComponentModel; using System.Windows.Forms; namespace test { public partial class frmB: Form { public frmB(BackgroundWorker worker) { InitializeComponent(); worker.ProgressChanged +=new ProgressChangedEventHandler(worker_ProgressChanged); worker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Close(); } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //lblStatus.Text = ""; } //工作完成后执行的事件 public void OnProcessCompleted(object sender, EventArgs e) { this.Close(); } } 二:在弹出的窗体里显示backgroundWorker的进度 1, backgroundWorker1的WorkerReportsProgress属性设置为true 2, 写如下事件 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } progressBar是进度条是你定义的变量..可以写在后台执行里面控制 3 .在后台执行里面 backgroundWorker1.ReportProgress(50); 其中50就是进度调的百分比. 比如一个循环循环100次 没次backgroundWorker1.ReportProgress(循环次数); 那么效果出来 。。 哈哈
标签:
原文地址:http://www.cnblogs.com/liushunli/p/4330632.html