Search code examples
c#messageboxtopmost

Why isn't MessageBox TopMost?


I recently found out that by default MessageBoxes were not the top most form when displayed by default and I was wondering if anyone knew any circumstances when you wouldn't want the messagebox to be shown on top of other windows?

I found the issue when I started to show splash screens whilst loading an application, and it looked like my program was still running but there was a MessageBox behind the splash screen that was waiting for input.. The splash screen was shown on a different thread to the thread that called the messagebox so I imagine this is why it didn't appear above the splash; but this still doesn't explain why MessageBox doesn't have the MB_TOPMOST flag by default?

Edit

To better clarify: in the end I had to do something similar to this in the end to make a messagebox, code isn't exactly correct as wrote from memory)

[DllImport("User32.dll")]
private int extern MessageBox(windowhandle, message, caption, flag);
public static void MessageBox(windowhandle, string message, string caption)
{
    MessageBox(windowhandle, message,caption, MB_TOPMOST);
}

Solution

  • To show the MessageBox on top-most of all for the application

    Code

    //Should be MessageBox.Show() below
    MessageBox.Show(this, "My top most message");
    

    Reason for not being MB_TOPMOST by default

    If MB_TOPMOST will be default then the MessageBox will show up in a 'system modal' mode and it will be exactly on top on that form and side effects are that the 'system modal' mode will cause the MessageBox to Block the windows until the message is dismissed normally it will be 'application modal' mode.

    Reference links

    1. MSDN forum - How to display a MessageBox as topmost window
    2. SO - C# MessageBox To Front When App is Minimized To Tray