MessageBox

The MessageBox function creates, displays, and operates a message box. A message box is a dialog box that displays a message to the user and prompts the user to respond.

Function Prototype

int MessageBox(
  HWND hWnd,
  LPCTSTR lpText,
  LPCTSTR lpCaption,
  UINT uType
);

Parameters

Parameter Type Description
hWnd HWND A handle to the owner window of the message box. This parameter can be NULL if the message box has no owner.
lpText LPCTSTR A null-terminated string that contains the message to be displayed.
lpCaption LPCTSTR A null-terminated string that specifies the title of the message box.
uType UINT A flag that determines the contents and behavior of the message box. This parameter can be a combination of flags from the following categories:
- Button types (e.g., MB_OK, MB_YESNO)
- Icon types (e.g., MB_ICONERROR, MB_ICONINFORMATION)
- Modality types (e.g., MB_APPLMODAL)
- Other options (e.g., MB_TOPMOST)

Return Value

If the function succeeds, the return value is one of the following integer values corresponding to the button that the user clicked:

Value Meaning
IDOK The OK button was selected.
IDCANCEL The Cancel button was selected.
IDABORT The Abort button was selected.
IDRETRY The Retry button was selected.
IDIGNORE The Ignore button was selected.
IDYES The Yes button was selected.
IDNO The No button was selected.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The uType parameter is crucial for customizing the message box. Here are some common flag combinations:

Button Types

Icon Types

Example Usage

Tip: When using MessageBox, ensure that the lpText and lpCaption parameters are valid null-terminated strings. For UNICODE builds, use LPTSTR and wide-character string literals (e.g., L"My Message").
// Display a simple information message box MessageBox(
  NULL, // No owner window
  L"Operation completed successfully.", // Message text
  L"Success", // Caption
  MB_OK | MB_ICONINFORMATION
);

// Display a confirmation dialog box int response = MessageBox(
  hWnd, // Owner window handle
  L"Are you sure you want to delete this item?", // Message text
  L"Confirm Deletion", // Caption
  MB_YESNO | MB_ICONQUESTION
);

if (response == IDYES) {
  // User clicked Yes, proceed with deletion
  MessageBox(hWnd, L"Item deleted.", L"Status", MB_OK | MB_ICONINFORMATION);
} else {
  // User clicked No or Cancelled
  MessageBox(hWnd, L"Deletion cancelled.", L"Status", MB_OK | MB_ICONINFORMATION);
}

See Also