因此,我在从应用程序的表单中删除控件时遇到了一些严重的问题。有点乱,但我什么也改变不了。我有一个窗体和一个独立的用户控件。该控件打开一个exe文件,并在加载该文件的字节时显示进度条。现在问题来了。我使用BackgroundWorker完成所有这些操作,当调用worker_DoWorkerCompleted方法时,原始表单应该显示一个MessageBox并删除该控件。
BackGround_Loader bgLoad = new BackGround_Loader();
bgLoad.Location = new Point(this.Width/2 - bgLoad.Width/2, this.Height/2 - bgLoad.Height/2);
this.Controls.Add(bgLoad);
bgLoad.BringToFront();
bgLoad.AddReferences(this.executableFile, this.SourceReader);
bgLoad.occuredEvent();首先,我将控件的位置设置在窗体本身的中间。然后我将该控件添加到窗体中,并将其放在最前面。之后,我发送可执行文件的路径和RichTextBox对它的引用。我使用occuredEvent启动BackgroundWorker本身。我的问题来了。当bgLoad中的后台工作人员进入DoWorkerCompleted状态时,我应该在表单中显示一个MessageBox。幸好我不知道该怎么做。它工作得非常完美,但是控件停留在窗体的中间。
发布于 2009-10-25 00:13:33
UI操作必须在主UI线程上执行。从后台工作线程引发的事件(显然)在不同的线程中。
您需要类似以下代码的代码:
private void backgroundWorker_DoWork(object sender, AlbumInfoEventArgs e)
{
// Check with an element on the form whether this is a cross thread call
if (dataGridView.InvokeRequired)
{
dataGridView.Invoke((MethodInvoker)delegate { AddToGrid(e.AlbumInfo); });
}
else
{
AddToGrid(e.AlbumInfo);
}
}在本例中,AddToGrid是我用来向DataGridView添加行的方法,但在您的示例中,它将是一个完成您所需操作的方法。
backgroundWorker_RunWorkerCompleted方法也是如此
查看此MSDN example
发布于 2009-10-25 05:11:05
我可以找到一个解决这个问题的方法,但我真的不喜欢它。在addReferences方法中,我传递了表单本身和bgLoad类的一个对象。然后在RunWorkerCompleted中,我检查控件是否在窗体上,如果在窗体上,则删除它。
bgLoad.AddReferences(this, bgLoad, this.executableFile, this.SourceReader);
...
private void worker_DoWorkerCompleted(object sender, DoWorkerEventArgs e) {
if(this.MainForm.Controls.Contains(this.Control) {
this.MainForm.Controls.Remove(this.Control);
}
}就像这样,它起作用了,但对我来说很糟糕。
https://stackoverflow.com/questions/1618349
复制相似问题