0

我有一个加载文件的方法。有时需要很长时间,所以我想向用户显示一个进度条窗口,他可以使用它最小化整个应用程序或取消进度。

我已经阅读了一堆关于 BackgroundWorkers 和 ProgressBars 的教程,但是当 ProgressBar 处于其他某种形式时,这些都没有涵盖这种情况。我不知道我应该什么时候打开新表单以及如何访问那里的进度条。

到目前为止,我已经尝试过:

主窗体:

private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
    ctlFolderSelectDialog dlg = new ctlFolderSelectDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        BackgroundWorker.RunWorkerAsync(dlg); // to pass some variables from ctlFolderSelectDialog
    }
}

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    Form_Dialogs.ProgressDialog progressDialog = new Form_Dialogs.ProgressDialog();
    progressDialog.ShowDialog(); // open the progress dialog window

    myClass.loadFiles((ctlFolderSelectDialog)e.Argument); // THE WORK

    progressDialog.Close(); // close the progress window - in here?
}

我的课:

public void loadFiles(ctlFolderSelectDialog dlg)
{
    ...
    files.Count() // somehow report this preliminary number of files to ProgressBar window - to set ProgressBar1.Maximum value
    ...
    foreach (file in files)
    {
        loadFile();
        ... // here I should somehow udpate the progressBar on the other window - performStep()
    }
}

进度对话框:

private void ProgressDialog_Load(object sender, EventArgs e)
{
    progressBar1.Value = 0;
    progressBar1.Maximum = 100; // how to get this value from myClass function? Pass in ProgressDialog contructor?
    progressBar1.Step = 1;
}

public void UpdateProgress(int progress)
{
    progressBar1.PerformStep();
}
4

1 回答 1

1

BackgroundWorkerProgressChanged支持通过事件更新进度。

loadFiles()方法内部,您需要在 % 和foreach循环调用内部计算进度backgroundWorker.ReportProgress(percentage)。这将引发ProgressChanged您可以从中获取事件参数的事件e.ProgressPercentage。[您将需要对BackgroundWorker内部loadFiles()方法的引用]

ProgressDialog您需要注册此活动的表格中。您可以在构造函数中传递,BackgroundWorker例如

public void ProgressDialog(BackgroundWorker worker)
{
   worker.ProgressChanged += ProgressDialog_ProgressChanged;
}

private void ProgressDialog_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   UpdateProgressBar(e.ProgressPercentage);
}

并以主要形式:

private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
    ctlFolderSelectDialog dlg = new ctlFolderSelectDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        BackgroundWorker.RunWorkerAsync(dlg); // to pass some variables fromctlFolderSelectDialog
        Form_Dialogs.ProgressDialog progressDialog = 
           new Form_Dialogs.ProgressDialog(BackgroundWorker); // Pass the BackgroundWorker instance
        progressDialog.ShowDialog(); // open the progress dialog window
        // No need to explicitly close it. A dialog form is destroyed when closed by the user.
    }
}

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    myClass.loadFiles((ctlFolderSelectDialog)e.Argument); // THE WORK
}
于 2013-05-08T23:54:30.377 回答