我是 C#.NET 的新手。我试图从我的主 UI 中创建一个带有进度条的表单来显示进度。我使用 BackgroundWorker 来调用它。我能够显示进度对话框,但不能更新进度条值。请在下面找到代码。
主界面:
namespace GC
{
public partial class MainUI : Form
{
private ProgressBar oProgressBar;
public MainUI()
{
InitializeComponent();
}
private void runButton_Click(object sender, EventArgs e)
{
oProgressBar = new ProgressBar();
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.RunWorkerAsync();
oProgressBar.ShowDialog();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//some work here
for (int i = 0; i < 20; i++)
backgroundWorker1.ReportProgress(i);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
oProgressBar.Close();
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
oProgressBar.progressBar1.Value = e.ProgressPercentage;
}
}
}
进度条 UI此表单包含进度条
namespace GC
{
public partial class ProgressBar : Form
{
public ProgressBar()
{
InitializeComponent();
}
}
}