Search code examples
c#winformsmessagebox

Can I show a MessageBox but still use the form?


It is possible that when I use:

MessageBox.Show("hello");

..to still use the form but the MessageBox is open like a second window? because currently, when I show the MessageBox, I need to first click yes or no then I can use my form again.


Solution

  • Yes, you can!

    If you simply want to display a MessageBox, don't care what happens with it, and don't want to wait until it's closed, you may launch it on a separate thread. The easiest way to do that would be using Task.Run().

    Here's an example:

    private void button1_Click(object sender, EventArgs e)
    {
        Task.Run(() => MessageBox.Show("hello"));
    
        // The remaining code will run without waiting for the MessageBox to be closed.
    }
    

    A couple of notes worth mentioning:

    • Only use this for simple message boxes where you don't care about the result. If you want to act based on the result and execute something (on the main thread), things get a little bit trickier.

    • You won't be able to keep the MessageBox on top of the form. Once you interact with the form, it will come on top. If you need to keep the MessageBox on top and still have the ability to interact with the form, a custom MessageBox (i.e., form) would be better in that case because you can set the Owner property to keep it on top.