MessageBox Function
int MessageBox(
_In_opt_ HWND hWnd,
_In_opt_ LPCSTR lpText,
_In_opt_ LPCSTR lpCaption,
_In_ UINT uType
);
The MessageBox
function creates, displays, and operates a message box. A message box is a modal dialog box that displays a specified message to the user, along with a specified icon and set of buttons.
Parameters
hWnd
-
A handle to the owner window of the message box. This parameter can be
NULL
if the message box has no owner. lpText
- A pointer to a null-terminated string that contains the message to be displayed.
lpCaption
-
A pointer to a null-terminated string that contains the desired caption for the message box. If this parameter is
NULL
, the caption is set to "Error". uType
- The content and behavior of the message box. This parameter can be a combination of flags that define the appearance of the message box, including the icons displayed and the buttons available.
Return Value
int
-
If the function succeeds, the return value is one of the following integer values corresponding to the button that the user clicked:
IDOK
,IDCANCEL
,IDABORT
,IDRETRY
,IDIGNORE
,IDYES
, orIDNO
.
If the function fails (for example, because it cannot create the message box), the return value is 0.
Remarks
The MessageBox
function can display various icons, such as information, warning, error, or question marks, by specifying appropriate flags in the uType
parameter. It also supports different button combinations like OK, OK/Cancel, Yes/No, etc.
When a message box is displayed, the user must respond to it before the application can continue execution. This makes message boxes suitable for displaying critical information or prompting for user confirmation.
Flags for uType
Parameter:
- Buttons:
MB_OK
,MB_OKCANCEL
,MB_YESNO
,MB_YESNOCANCEL
,MB_ABORTRETRYIGNORE
,MB_RETRYCANCEL
. - Icons:
MB_ICONERROR
(orMB_ICONSTOP
),MB_ICONQUESTION
,MB_ICONWARNING
(orMB_ICONEXCLAMATION
),MB_ICONINFORMATION
(orMB_ICONASTERISK
). - Default Button:
MB_DEFBUTTON1
,MB_DEFBUTTON2
,MB_DEFBUTTON3
,MB_DEFBUTTON4
. - Modality:
MB_APPLMODAL
(default),MB_SYSTEMMODAL
.
Example Usage
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
int msgboxID = MessageBox(
NULL,
"This is the message text.",
"My Application",
MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2
);
switch (msgboxID)
{
case IDYES:
// User clicked Yes
break;
case IDNO:
// User clicked No
break;
}
return 0;
}
Important Notes
When specifying the uType
parameter, you typically combine one button flag with one icon flag. If no button flag is specified, MB_OK
is assumed.
For more detailed information on all available flags and their combinations, please refer to the official Microsoft documentation.