【发布时间】:2010-12-01 01:15:36
【问题描述】:
我有以下问题:
我有一个名为 MainForm 的表单。我要在这张表格上进行长时间的手术。
虽然这个漫长的操作正在进行,但我需要在 MainForm 顶部显示另一个名为 ProgressForm 的操作。
ProgressForm 包含一个进度条,在进行长操作时需要更新该进度条。
长操作完成后,ProgressForm应该会自动关闭。
我写了以下代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ClassLibrary
{
public class MyClass
{
public static string LongOperation()
{
Thread.Sleep(new TimeSpan(0,0,30));
return "HelloWorld";
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BackgroungWorker__HelloWorld
{
public partial class ProgressForm : Form
{
public ProgressForm()
{
InitializeComponent();
}
public ProgressBar ProgressBar
{
get { return this.progressBar1; }
set { this.progressBar1 = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ClassLibrary;
namespace BackgroungWorker__HelloWorld
{
public partial class MainForm : Form
{
ProgressForm f = new ProgressForm();
public MainForm()
{
InitializeComponent();
}
int count = 0;
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (f != null)
{
f.ProgressBar.Value = e.ProgressPercentage;
}
++count;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (f == null)
{
f = new ProgressForm();
}
f.ShowDialog();
//backgroundWorker1.ReportProgress(100);
MyClass.LongOperation();
f.Close();
}
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
this.Close();
}
}
}
我找不到更新progressBar 的方法。
我应该把backgroundWorker1.ReportProgress()放在哪里,我应该怎么称呼它?
我不能对MyClass 进行任何更改,因为我不知道会发生什么或需要多长时间才能完成我的应用程序这一层的操作。
谁能帮帮我?
【问题讨论】:
标签: c# winforms progress-bar backgroundworker