1. 程式人生 > >C# 簡單的等待提示框(BackgroundWorker)

C# 簡單的等待提示框(BackgroundWorker)

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        System.ComponentModel.BackgroundWorker _worker = new System.ComponentModel.BackgroundWorker();
        Progress _fmProgress = null;
        public Form1()
        {
            InitializeComponent();
            //註冊執行事件
            _worker.WorkerReportsProgress = true;
            _worker.WorkerSupportsCancellation = true;
            _worker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            _worker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgessChanged);
            _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_WorkerCompleted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //等待小畫面
            _fmProgress = new Progress();
            //執行等待功能
            _worker.RunWorkerAsync(null);
        }
        public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //記錄執行進度
            _worker.ReportProgress(0);
            //作業內容
            Thread.Sleep(2000);
        }

        public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e)
        {
            //執行前開啟小畫面
            _fmProgress.Show(this);
        }

        public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //執行後關閉畫面
            _fmProgress.Dispose();
        }
    }
}