en:docs:win16:api:user:messagebox

This is part of Win16 API which allow to create versions of program from one source code to run under OS/2 and Win16. Under OS/2 program can be running under Win-OS/2 if program is Windows NE executable, and with help on Windows Libraries for OS/2, if it is OS/2 NE executable. Here is a WLO to OS/2 API mapping draft

2021/09/01 04:23 · prokushev · 0 Comments

MessageBox

Brief

The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.

Syntax

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

Parameters

  • hWnd - Handle to the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.
  • lpText - Pointer to a null-terminated string containing the message to be displayed. If the string consists of more than one line, you can separate the lines using a carriage return and/or linefeed character between each line.
  • lpCaption - Pointer to a null-terminated string used for the dialog box title. If this parameter is NULL, the default title “Error” is used.
  • uType - Contains a set of bit flags that determine the content and behavior of the dialog box. This parameter can be a combination of flags from the following groups:

Buttons:

  • MB_ABORTRETRYIGNORE - Contains Abort, Retry, and Ignore buttons.
  • MB_OK - Contains one push button: OK (default).
  • MB_OKCANCEL - Contains OK and Cancel buttons.
  • MB_RETRYCANCEL - Contains Retry and Cancel buttons.
  • MB_YESNO - Contains Yes and No buttons.
  • MB_YESNOCANCEL - Contains Yes, No, and Cancel buttons.

Icons:

  • MB_ICONEXCLAMATION / MB_ICONWARNING - Exclamation-point icon.
  • MB_ICONINFORMATION / MB_ICONASTERISK - Information icon (i in a circle).
  • MB_ICONQUESTION - Question-mark icon.
  • MB_ICONSTOP / MB_ICONERROR / MB_ICONHAND - Stop-sign icon.

Default Button:

  • MB_DEFBUTTON1 - First button is default (default).
  • MB_DEFBUTTON2 - Second button is default.
  • MB_DEFBUTTON3 - Third button is default.

Modality:

  • MB_APPLMODAL - Application-modal (default). User must respond to the message box before continuing work in the current window.
  • MB_SYSTEMMODAL - System-modal (topmost). All applications are suspended until user responds.
  • MB_TASKMODAL - Task-modal. Similar to MB_APPLMODAL but used when the calling application has no window handle.

Other:

  • MB_SETFOREGROUND - Message box becomes the foreground window.
  • MB_TOPMOST - Message box is placed above all non-topmost windows.

Return Code

The function returns zero if there is not enough memory to create the message box. If the call succeeds, the return value is one of the following menu-item values:

  • IDABORT - Abort button was selected.
  • IDCANCEL - Cancel button was selected.
  • IDIGNORE - Ignore button was selected.
  • IDNO - No button was selected.
  • IDOK - OK button was selected.
  • IDRETRY - Retry button was selected.
  • IDYES - Yes button was selected.

Notes

  • The system supports only a limited number of message boxes simultaneously.
  • When using the MB_SYSTEMMODAL flag, the message box appears on top of all windows and is typically used for critical errors requiring immediate user attention.
  • If a message box is created without an owner window (hWnd = NULL), it behaves as an independent window.
  • The message box is modal and does not return control until the user closes it by pressing a button.

Example Code

C Binding

#include <windows.h>
 
int PASCAL WinMain(HANDLE hInstance, HANDLE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
    // Simple information message box
    MessageBox(NULL,
               "Hello, world! This is a message from Janus.",
               "Win16 Example",
               MB_OK | MB_ICONINFORMATION);
 
    // Question message box with Yes/No/Cancel
    int result = MessageBox(NULL,
                            "Do you want to save changes?",
                            "Confirmation",
                            MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON1);
 
    // Handle the result
    if (result == IDYES)
    {
        MessageBox(NULL, "You chose Yes", "Result", MB_OK | MB_ICONINFORMATION);
    }
    else if (result == IDNO)
    {
        MessageBox(NULL, "You chose No", "Result", MB_OK | MB_ICONINFORMATION);
    }
    else if (result == IDCANCEL)
    {
        MessageBox(NULL, "You chose Cancel", "Result", MB_OK | MB_ICONWARNING);
    }
 
    // Error message example
    MessageBox(GetActiveWindow(),
               "File not found. Please check the path.",
               "Error",
               MB_OK | MB_ICONSTOP | MB_SYSTEMMODAL);
 
    return 0;
}

MASM Binding

; Example for MASM (Microsoft Macro Assembler)
; Assemble with: MASM /MX program.asm
; Link with: LINK program.obj,,,libw.lib,,
 
.MODEL LARGE
.386
 
INCLUDE windows.inc
 
.DATA
    msg_hello    DB "Hello, world!", 0
    cap_hello    DB "Greeting", 0
 
    msg_question DB "Continue operation?", 0
    cap_question DB "Question", 0
 
    msg_yes      DB "You pressed Yes", 0
    msg_no       DB "You pressed No", 0
    msg_cancel   DB "Operation cancelled", 0
    cap_result   DB "Result", 0
 
.CODE
START PROC FAR
    ; Initialize
    push    ds
    pop     ax
    xor     ax, ax
 
    ; Simple message box
    push    MB_OK OR MB_ICONINFORMATION    ; uType
    push    OFFSET cap_hello                 ; lpCaption
    push    OFFSET msg_hello                  ; lpText
    push    0                                  ; hWnd = NULL
    call    MessageBox
 
    ; Question message box
    push    MB_YESNOCANCEL OR MB_ICONQUESTION ; uType
    push    OFFSET cap_question                 ; lpCaption
    push    OFFSET msg_question                  ; lpText
    push    0                                      ; hWnd = NULL
    call    MessageBox
 
    ; Check result (result is in AX)
    cmp     ax, IDYES
    je      show_yes
    cmp     ax, IDNO
    je      show_no
    cmp     ax, IDCANCEL
    je      show_cancel
    jmp     exit_program
 
show_yes:
    push    MB_OK OR MB_ICONINFORMATION
    push    OFFSET cap_result
    push    OFFSET msg_yes
    push    0
    call    MessageBox
    jmp     exit_program
 
show_no:
    push    MB_OK OR MB_ICONINFORMATION
    push    OFFSET cap_result
    push    OFFSET msg_no
    push    0
    call    MessageBox
    jmp     exit_program
 
show_cancel:
    push    MB_OK OR MB_ICONWARNING
    push    OFFSET cap_result
    push    OFFSET msg_cancel
    push    0
    call    MessageBox
 
exit_program:
    ; Exit program
    mov     ax, 4C00h
    int     21h
START ENDP
 
END START

See also

Group Functions
Module Management GetVersion GetModuleHandle GetModuleUsage GetModuleFileName GetProcAddress MakeProcInstance FreeProcInstance GetInstanceData Catch Throw GetCodeHandle LoadLibrary FreeLibrary
Global Memory Management GlobalAlloc GlobalCompact GlobalDiscard GlobalFree GlobalLock GlobalReAlloc GlobalSize GlobalUnlock GlobalFlags
Local Memory Management LocalInit LocalAlloc LocalCompact LocalDiscard LocalFree LocalLock LocalFreeze LocalMelt LocalReAlloc LocalSize LocalUnlock LocalHandleDelta LockData UnlockData LocalFlags
Task Scheduling GetCurrentTask Yield SetPriority
Resource Management AddFontResource RemoveFontResource LoadBitmap LoadCursor LoadIcon LoadMenu LoadString LoadAccelerators FindResource LoadResource AllocResource LockResource FreeResource AccessResource SizeofResource SetResourceHandler
String Manipulation AnsiUpper AnsiLower AnsiNext AnsiPrev AnsiUpperBuff AnsiLowerBuff lstrcmp lstrcmpi IsCharAlpha IsCharAlphaNumeric IsCharUpper IsCharLower _wsprintf wvsprintf
Atom Management InitAtomTable AddAtom DeleteAtom FindAtom GetAtomName GlobalAddAtom GlobalDeleteAtom GlobalFindAtom GlobalGetAtomName
Initialization Files GetProfileInt GetProfileString WriteProfileString
Debugging FatalExit
File Input/Output _lopen _lcreat _llseek _lread _lwrite _lclose OpenFile GetTempFileName GetTempDrive
Registry RegOpenKey RegCreateKey RegCloseKey RegDeleteKey RegSetValue RegQueryValue RegEnumKey
Window Management CreateWindow CreateWindowEx DestroyWindow ShowWindow CloseWindow OpenIcon MoveWindow SetWindowPos BringWindowToTop GetWindow GetParent SetParent GetNextWindow GetTopWindow GetWindowRect GetClientRect AdjustWindowRect AdjustWindowRectEx EnableWindow IsWindowEnabled IsWindowVisible IsIconic IsZoomed IsWindow IsChild FindWindow EnumWindows EnumChildWindows EnumTaskWindows GetDesktopWindow GetDesktopHwnd WindowFromPoint ChildWindowFromPoint GetWindowText SetWindowText GetWindowTextLength GetClassName GetWindowLong SetWindowLong GetWindowWord SetWindowWord GetWindowTask GetWindowPlacement SetWindowPlacement ArrangeIconicWindows CascadeChildWindows TileChildWindows ShowOwnedPopups AnyPopup GetLastActivePopup SetActiveWindow GetActiveWindow SetFocus GetFocus SetCapture GetCapture ReleaseCapture SetSysModalWindow GetSysModalWindow LockWindowUpdate RedrawWindow UpdateWindow InvalidateRect InvalidateRgn ValidateRect ValidateRgn GetUpdateRect GetUpdateRgn ExcludeUpdateRgn BeginDeferWindowPos DeferWindowPos EndDeferWindowPos FlashWindow
Message Handling GetMessage PeekMessage PostMessage PostAppMessage SendMessage ReplyMessage InSendMessage WaitMessage TranslateMessage DispatchMessage GetMessagePos GetMessageTime GetMessageExtraInfo PostQuitMessage RegisterWindowMessage SetMessageQueue GetQueueStatus GetInputState QuerySendMessage
Painting and Drawing BeginPaint EndPaint GetDC GetDCEx GetWindowDC ReleaseDC DrawText GrayString TabbedTextOut GetTabbedTextExtent FillRect InvertRect FrameRect DrawFocusRect DrawIcon ScrollDC ScrollWindow ScrollWindowEx FillWindow PaintRect GetControlBrush
Menus CreateMenu CreatePopupMenu DestroyMenu GetMenu SetMenu GetSystemMenu GetSubMenu AppendMenu InsertMenu ModifyMenu DeleteMenu RemoveMenu ChangeMenu CheckMenuItem EnableMenuItem HiliteMenuItem GetMenuState GetMenuString GetMenuItemCount GetMenuItemID DrawMenuBar TrackPopupMenu GetMenuCheckMarkDimensions SetMenuItemBitmaps IsMenu
Clipboard OpenClipboard CloseClipboard EmptyClipboard GetClipboardOwner GetOpenClipboardWindow SetClipboardData GetClipboardData CountClipboardFormats EnumClipboardFormats RegisterClipboardFormat GetClipboardFormatName IsClipboardFormatAvailable GetPriorityClipboardFormat SetClipboardViewer GetClipboardViewer ChangeClipboardChain
Caret CreateCaret DestroyCaret SetCaretPos GetCaretPos HideCaret ShowCaret SetCaretBlinkTime GetCaretBlinkTime
Cursor and Icon SetCursor GetCursor SetCursorPos GetCursorPos ShowCursor ClipCursor GetClipCursor LoadCursor LoadIcon CreateCursor CreateIcon CopyCursor CopyIcon DestroyCursor DestroyIcon CreateCursorIconIndirect
Scroll Bars SetScrollPos GetScrollPos SetScrollRange GetScrollRange ShowScrollBar EnableScrollBar CalcChildScroll
Dialog Boxes DialogBox DialogBoxIndirect DialogBoxParam DialogBoxIndirectParam CreateDialog CreateDialogIndirect CreateDialogParam CreateDialogIndirectParam EndDialog GetDlgItem SetDlgItemText GetDlgItemText SetDlgItemInt GetDlgItemInt CheckDlgButton IsDlgButtonChecked CheckRadioButton SendDlgItemMessage GetNextDlgGroupItem GetNextDlgTabItem GetDlgCtrlID IsDialogMessage MapDialogRect GetDialogBaseUnits DefDlgProc DlgDirList DlgDirListComboBox DlgDirSelect DlgDirSelectEx DlgDirSelectComboBox DlgDirSelectComboBoxEx
Device Context Management GetDC GetDCEx GetWindowDC ReleaseDC SaveDC RestoreDC CreateDC CreateCompatibleDC DeleteDC ResetDC
Coordinates and Transformations SetMapMode GetMapMode SetWindowOrg GetWindowOrg SetWindowExt GetWindowExt SetViewportOrg GetViewportOrg SetViewportExt GetViewportExt OffsetWindowOrg OffsetViewportOrg ScaleWindowExt ScaleViewportExt DPtoLP LPtoDP
Drawing Functions SetPixel GetPixel MoveTo LineTo Polyline Polygon PolyPolygon Rectangle RoundRect Ellipse Arc Chord Pie FloodFill ExtFloodFill DrawFocusRect PatBlt BitBlt StretchBlt StretchDIBits SetDIBits GetDIBits SetDIBitsToDevice
Regions CreateRectRgn CreateRectRgnIndirect CreateRoundRectRgn CreateEllipticRgn CreateEllipticRgnIndirect CreatePolygonRgn CreatePolyPolygonRgn CombineRgn EqualRgn OffsetRgn FillRgn FrameRgn InvertRgn PaintRgn SelectClipRgn ExcludeClipRect IntersectClipRect OffsetClipRgn GetClipBox GetRgnBox PtInRegion RectInRegion SetRectRgn
Bitmaps CreateBitmap CreateBitmapIndirect CreateCompatibleBitmap CreateDiscardableBitmap CreateDIBitmap CreateDIBPatternBrush SetBitmapBits GetBitmapBits SetBitmapDimension GetBitmapDimension
Brushes and Pens CreateSolidBrush CreateHatchBrush CreatePatternBrush CreateBrushIndirect CreatePen CreatePenIndirect SetBrushOrg GetBrushOrg SelectObject GetObject DeleteObject GetStockObject UnrealizeObject
Fonts and Text CreateFont CreateFontIndirect CreateScalableFontResource AddFontResource RemoveFontResource EnumFonts EnumFontFamilies GetTextMetrics GetTextExtent GetTextFace GetCharWidth GetCharABCWidths GetOutlineTextMetrics GetGlyphOutline GetKerningPairs SetTextColor GetTextColor SetBkColor GetBkColor SetBkMode GetBkMode SetTextAlign GetTextAlign SetTextCharacterExtra GetTextCharacterExtra SetTextJustification TextOut ExtTextOut TabbedTextOut GetTabbedTextExtent
Metafiles CreateMetaFile CloseMetaFile DeleteMetaFile CopyMetaFile GetMetaFile GetMetaFileBits SetMetaFileBits PlayMetaFile PlayMetaFileRecord EnumMetaFile IsValidMetaFile
Printing StartDoc EndDoc StartPage EndPage SetAbortProc AbortDoc QueryAbort OpenJob CloseJob DeleteJob WriteSpool StartSpoolPage EndSpoolPage SpoolFile
Palettes CreatePalette SelectPalette RealizePalette GetPaletteEntries SetPaletteEntries ResizePalette AnimatePalette UpdateColors GetNearestPaletteIndex GetNearestColor SetSystemPaletteUse GetSystemPaletteUse GetSystemPaletteEntries
Device Capabilities GetDeviceCaps GetRasterizerCaps GetEnvironment SetEnvironment GetAspectRatioFilter Escape CreateIC
Miscellaneous GDI SetROP2 GetROP2 SetPolyFillMode GetPolyFillMode SetStretchBltMode GetStretchBltMode SetMapperFlags GetMapperFlags LineDDA MulDiv GetCurrentPosition GetBoundsRect SetBoundsRect FastWindowFrame
Timer SetTimer KillTimer GetTickCount GetTimerResolution GetCurrentTime
Hooks SetWindowsHook SetWindowsHookEx UnhookWindowsHook UnhookWindowsHookEx CallNextHookEx DefHookProc CallMsgFilter
Communications OpenComm CloseComm ReadComm WriteComm SetCommState GetCommState GetCommError TransmitCommChar SetCommEventMask GetCommEventMask SetCommBreak ClearCommBreak UngetCommChar BuildCommDCB EscapeCommFunction FlushComm EnableCommNotification
Networking (WNet) WNetErrorText WNetOpenJob WNetCloseJob WNetAbortJob WNetHoldJob WNetReleaseJob WNetCancelJob WNetSetJobCopies WNetWatchQueue WNetUnwatchQueue WNetLockQueueData WNetUnlockQueueData WNetGetConnection WNetGetCaps WNetDeviceMode WNetBrowseDialog WNetGetUser WNetAddConnection WNetCancelConnection WNetGetError WNetGetErrorText WNetEnable WNetDisable WNetRestoreConnection WNetWriteJob WNetConnectDialog WNetDisconnectDialog WNetConnectionDialog WNetViewQueueDialog WNetPropertyDialog WNetGetDirectoryType WNetDirectoryNotify WNetGetPropertyText
System Information GetSystemMetrics GetSysColor SetSysColors SystemParametersInfo GetFreeSystemResources GetSystemDebugState GetDoubleClickTime SetDoubleClickTime SwapMouseButton GetKeyState GetAsyncKeyState GetKeyboardState SetKeyboardState mouse_event GetMouseEventProc EnableHardwareInput IsUserIdle LockInput MessageBeep WinHelp
Window Classes RegisterClass RegisterClassEx UnregisterClass GetClassInfo GetClassInfoEx GetClassWord SetClassWord GetClassLong SetClassLong GetClassName
Window Properties SetProp GetProp RemoveProp EnumProps
MDI Support DefFrameProc DefMDIChildProc TranslateMDISysAccel
Drivers OpenDriver CloseDriver SendDriverMessage GetDriverModuleHandle GetDriverInfo GetNextDriver DefDriverProc
Miscellaneous InitApp ExitWindows ExitWindowsExec OLDEXITWINDOWS BEAR11 BEAR86 BEAR182 UserSeeUserDo OldSetDeskPattern SetRect SetRectEmpty CopyRect IsRectEmpty PtInRect OffsetRect InflateRect IntersectRect UnionRect EqualRect SubtractRect
2022/11/17 15:22 · prokushev · 0 Comments