在C#中加载时生成进度条

时间:2013-08-13 01:47:20

标签: c# winforms

我有以下代码,只是在加载时显示消息文本框:

    private void button3_Click_1(object sender, EventArgs e)
    {
        int i;
        BackgroundWorker bw = new BackgroundWorker();

        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

        msgForm = new Form2();  //Form2 is showing a message "Please Wait..."

        try
        {
                bw.RunWorkerAsync(comboBox15.Text);

                msgForm.StartPosition = FormStartPosition.CenterParent;
                msgForm.ShowDialog();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        string PrtAdd = e.Argument.ToString();

        Loading(PrtAdd); //This is the function of my loading.
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        msgForm.Close();
    }

我的装载有时需要2-3分钟。因此,如果只显示一个静态消息框,用户可能会认为我的程序可能会挂起。

我想通过在加载时添加进度条来改进这一点。你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

也许是这样的事情?

public partial class Form1 : Form
{
    private Form2 _frm2;

    public Form1() {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += BwOnDoWork;
        bw.RunWorkerCompleted += BwOnRunWorkerCompleted;
        bw.RunWorkerAsync();

        _frm2 = new Form2(bw);
        _frm2.StartPosition = FormStartPosition.CenterParent;
        _frm2.ShowDialog();
    }

    private void BwOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
    {
       if (_frm2 != null)
       {
           _frm2.Close();
       }
    }

    private void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
    {
        var bw = sender as BackgroundWorker;
        var i = 0;
        while (i < 100 && !bw.CancellationPending)
        {
            bw.ReportProgress(i);
            Thread.Sleep(100);
            i++;
        }
    }
}

public partial class Form2 : Form
{
    private BackgroundWorker _bw;

    public Form2() {
        InitializeComponent();
    }

    public Form2(BackgroundWorker bw) : this()
    {
        _bw = bw;
        _bw.ProgressChanged += BwOnProgressChanged;
    }

    private void BwOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs)
    {
        progressBar1.Value = progressChangedEventArgs.ProgressPercentage;
    }

    private void button1_Click(object sender, EventArgs e) {
        _bw.CancelAsync();
    }
}