Search code examples
cwindowswinapimessagebox

How can I cause my MessageBox to pop up on top of all forms?


I am currently providing information to the user with a message box in my C program, but the message box is appearing behind all other forms of my application.

How can I bring it forward so that it appears in front of all my forms, or set its parent?

Here is the code I'm currently using to show the message box:

MessageBox(0,error_msg, "Error - No Algorithm", MB_OK );

Solution

  • The reason it's appearing behind all forms now is because you've not specified an owner window. That causes it to appear directly on top of the desktop window. The problem is that your other windows are already covering up the desktop window, so they blissfully continue to cover up your message box, too.

    The solution, as you suspect, is to specify one of your windows as the owner for the message box. You do that by specifying their window handle (HWND) as the first argument to the function:

    MessageBox(hWnd,                    // the window handle for your owner window
               error_msg,               // the message to be displayed
               "Error - No Algorithm",  // the title
               MB_OK);                  // flags indicating contents and behavior
    

    The documentation provides additional information.