创建一个不会停止代码的MessageBox?

soo*_*ise 18 c# messagebox

好的,我正在寻找一些非常简单的东西:创建一个不会停止我的代码的MessageBox.

我猜我必须创建一个不同的线程或什么?请告知最佳方法.

谢谢!

Bri*_*eon 14

您可以通过在单独的线程上调用它来启动另一个消息泵.MessageBox.Show泵消息所以没有电话就可以安全Application.Run.

public void ShowMessageBox()
{
  var thread = new Thread(
    () =>
    {
      MessageBox.Show(...);
    });
  thread.Start();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我可能应该提一下,我不建议这样做.它可能会导致其他问题.例如,如果您有两个线程在传递消息,那么消息框可能会卡在另一个表单后面,如果表单正在等待某人关闭消息框,则无法使其消失.你真的应该试图找出解决问题的另一种方法.

  • @Markus:那也可以做到这一点,除了它会挂掉一个`ThreadPool`线程,这通常不是一个好习惯. (2认同)

Are*_*ren 10

No, You're going to have to make your own message box form. the MessageBox class only supports behavior similar to .ShowDialog() which is a modal operation.

Just create a new form that takes parameters and use those to build up a styled message box to your liking.


Update 2014-07-31

In the spirit of maintaining clarity for anyone else who finds this through google I'd like to take a second to explain this a bit more:

Under the hood MessageBox is a fancy C# Wrapper around the Windows SDK user32.dll MessageBox Function and thus behaves exactly the same way (after converting .NET Enums into the integers that represent the same thing in the system call.

这意味着当你调用时,调用MessageBox.Show()将被封送到操作系统并阻塞当前线程,直到选择一个选项或窗口被终止.为了防止代码被暂停,您需要在单独的线程上启动消息框,但这将意味着将返回从消息框返回的任何结果(//确定/取消 /等等...)到负责调用消息框的单独线程.

如果你按照这种方式启动此消息框的结果,你必须将结果发送回UI Thread for Thread Saftey.

或者,您可以在WinForms/WPF中创建自己的消息框表单,并使用该.Show()方法调用它.按钮上的任何单击事件都将在UI线程上执行,您不必将调用分派回UI线程来操纵UI中的内容.