C#如何制作返回DialogResult的异步MessageBox?

时间:2016-01-17 19:22:06

标签: c# winforms asynchronous messagebox dialogresult

我的MessageBox是异步的,但是如何返回DialogResult?

这是我的代码:

class AsyncMessageBox
{
    private delegate void ShowMessageBoxDelegate(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage);
    // Method invoked on a separate thread that shows the message box.
    private static void ShowMessageBox(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage)
    {
        MessageBox.Show(strMessage, strCaption, enmButton, enmImage);
    }
    // Shows a message box from a separate worker thread.
    public void ShowMessageBoxAsync(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage)
    {
        ShowMessageBoxDelegate caller = new ShowMessageBoxDelegate(ShowMessageBox);
        caller.BeginInvoke(strMessage, strCaption, enmButton, enmImage, null, null);
    }
}

1 个答案:

答案 0 :(得分:5)

如果要使用非阻止消息框的对话框结果并根据结果执行作业:

Task.Run(() =>
{
    var dialogResult=  MessageBox.Show("Message", "Title", MessageBoxButtons.OKCancel);
    if (dialogResult == System.Windows.Forms.DialogResult.OK)
        MessageBox.Show("OK Clicked");
    else
        MessageBox.Show("Cancel Clicked");
});

注意:

  • Task.Run之后的代码会立即运行,而不管消息框如何。