C#, Windows Form, Messagebox on top not working

Alice picture Alice · Apr 9, 2013 · Viewed 12.3k times · Source

I've some MessageBox that I code like this:

MessageBox.Show(new Form(){TopMost=true, TopLevel=True}, "Message","Title", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

For a better example, I do this for the FormClosing Event:

private void Example_FormClosing(object sender, FormClosingEventArgs e){
MessageBox.Show(new Form(){TopMost=true, TopLevel=True}, "Really close?"," Program", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}

But, almost every time I've to change of Window on my computer (like return on Visual Studio) before seeing my messagebox and it's not user-friendly and really annoying.

I verified that my principal form was not in TopMost=true, I tried just the TopMost or just the TopLevel,the StartPosition=FormStartPosition.CenterScreen but nothing worked.

[Update]

I tried:

 private void Example_FormClosing(object sender, FormClosingEventArgs e){
    MessageBox.Show(this.Owner, "Really close?"," Program", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
    }

I'd like to have my messageBox on the front of my window and not have to change of window to see it because it's like behind the current window.

Have you an idea to resolve this problem?

Answer

Matthew Watson picture Matthew Watson · Apr 9, 2013

Do it like this:

MessageBox.Show(
    "Message", 
    "Title", 
    MessageBoxButtons.YesNo, 
    MessageBoxIcon.Warning, 
    MessageBoxDefaultButton.Button1, 
    MessageBoxOptions.DefaultDesktopOnly);

It will put it in front of all other windows, including those from other processes (which is what I think you're asking for).

The critical parameter is MessageBoxOptions.DefaultDesktopOnly. Note that this will parent the message box to the default desktop, causing the application calling MessageBox.Show() to lose focus.

(You should really reserve this behaviour for critical messages.)

Alternatively, if your application has a window, call this.BringToFront() before showing the message box by calling MessageBox.Show() with the first parameter set to this. (You'd call this from the window form class).