Form 没有在 backgroundworker 中显示为 Dialog?
这是我的代码:
//From Form1
private void backgroundWorkerResult_DoWork(object sender, DoWorkEventArgs e)
{
//do something here
backgroundWorkerResult.ReportProgress(100);
frmMessageBox frmMsgBox = new frmMessageBox();
frmMsgBox.ShowDialog();
}
即使我已经将 frmMsgBox
显示为对话框,我仍然可以单击应该不是的 Form1
吗?如何解决这个问题?
最佳答案
我创建了一个简单的代码示例,您可以使用它来了解后台工作人员的工作方式。将代码复制到测试窗体中,并添加以下控件
- 标签控件 - 将其命名为“lblStatus”
- 进度条控件 - 它应该命名为 progressBar1。
- 添加两个名为“btnStartAsyncOperation”和“btnCancel”的按钮,并链接它们的点击事件。
基本上您应该在RunWorkerCompleted 事件中显示结果
public partial class Form1 : Form
{
BackgroundWorker backgroundWorker;
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker {WorkerReportsProgress = true, WorkerSupportsCancellation = true};
backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
}
void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
lblStatus.Text = "Task Cancelled.";
else if (e.Error != null)
lblStatus.Text = "Error - " + e.Error.Message;
else
lblStatus.Text = "Task Completed...";
btnStartAsyncOperation.Enabled = true;
btnCancel.Enabled = false;
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(100);
backgroundWorker.ReportProgress(i);
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
backgroundWorker.ReportProgress(0);
return;
}
}
backgroundWorker.ReportProgress(100);
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
btnStartAsyncOperation.Enabled = false;
btnCancel.Enabled = true;
backgroundWorker.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
}
}
}
根据 OP 的评论编辑
在 DoWork 事件中,按如下方式设置您的字符串
e.Result = "Your String";
并在 RunWorkerCompleted 事件中
string muResult = Convert.ToString(e.Result);
注意: e.Result 是一个对象,因此您甚至可以在其中设置具有多个属性的自定义类。
关于c# - 表单在 backgroundworker 中不显示为对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115980/