Search code examples
c#winformsasynchronousmessageboxdialogresult

C# How to make async MessageBox that returns DialogResult?


My MessageBox is async, but how can I return DialogResult?

Here is my code:

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);
    }
}

Solution

  • If you want to use the dialog result of a non-blocking message box and perform a job based on the result:

    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");
    });
    

    Note:

    • The code after Task.Run immediately runs regardless of messagebox.