Search code examples
winformsvisual-c++replacemessagebox

In forms application, is there any Alternative to MsgBox?


I like how MsgBox stops all further processing until it's clicked but I don't like how it pops that little msgbox in the middle of the screen.

Is there a way to do something like a msgbox but keep it on my Form (which is always in view) so I can go ahead and click a button on the form instead of having to bring the little msgbox window on top of windows that may be covering it.

I use the msgbox to inform me that a certain situation has happened, which I manually fix and when I'm done I click the MsgBox to continue processing. It'd be nice to have this button right on the form.


Solution

  • which I then have bring to the front if there is a window covering it

    That shouldn't happen, but can happen if you display the message box from a thread in your program. The window has the desktop as the parent and has no Z-order relationship with the windows in your user interface. And yes, can easily disappear behind the window of another app, including your own.

    There's a MessageBoxOptions option that isn't exposed in Winforms, MB_TOPMOST, which ensures the window is top-most. You'd use it like this:

                MessageBox.Show("text", "caption", MessageBoxButtons.OK,
                    MessageBoxIcon.Information, MessageBoxDefaultButton.Button1,
                    (MessageBoxOptions)0x40000);    // use MB_TOPMOST
    

    But by far the best thing to do is to display the message box on your UI thread. Use Control.Invoke() to do so. That way the other windows of your app are disabled, no way for the user to not notice the box.

    Still one problem with this, the user won't expect the box to show up since it is shown asynchronously from anything she does. Which means the box can easily get dismissed by accident when the user just happened to press the Enter or Space key. Or clicked at just the wrong spot. Nothing much you can do about that.

    Centering the box in your main window is technically possible, but fugly to do. Check this answer.