从Form1作为父级的异步线程调用MessageBox

单击form1上的button1后,程序正在检查新版本是否可用(通过互联网),但是在新线程中执行此操作(在检查期间不冻结表单)。
当找到新版本时,会显示相应的MessageBox ,但它没有父级(因为它是从线程调用的,而不是直接从form1调用的)。

如何使用form1作为父级显示MessageBox

 this.Invoke(new Action(() => { MessageBox.Show(this, "text"); })); 

这将切换到主线程并显示带有form1 parent的MessageBox。

虽然所选答案提供了一种从异步线程显示MessageBox的好方法,但它不处理您想要从显示的特定MessageBox检索DialogResult情况。

如果您希望从Form顶部显示的调用MessageBox返回DialogResult 。 然后,您需要使用Func委托而不是Action委托。

Func具有返回值时, Action委托总是返回void。

这是我设计用于处理此特定方案的一个小方法:

 private DialogResult BackgroundThreadMessageBox(IWin32Window owner, string text) { if (this.InvokeRequired) { return (DialogResult) this.Invoke(new Func( () => { return MessageBox.Show(owner, text); })); } else { return MessageBox.Show(owner, text); } } 

虽然这通常不被认为是最佳实践或设计,但它可以在紧要关头工作。

  if ( Form1.InvokeRequired ) { Form1.Invoke((Action)delegate{MessageBox.Show(Form1,"Hello");}); } 

尝试使用背景工作者 。

 private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { //Helper thread: Long during task } private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //We're in the main thread: Show your messagebox } 

在我的情况下,我在另一个类,并有一个文本框的参考,所以我使用下面的代码:

 _txtResultado.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate () { MessageBox.Show("My message!"); }));