Making a simple C++/Win32 GUI application with MinGW – Part 2: Learning the basics

Making some simple programs is a good way of getting used to the Win32 API. Here’s the code for a basic application that shows a simple message box.

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

                   LPSTR lpCmdLine, int nCmdShow)

{

    LPCWSTR myText = L"Text for the message box";

    LPCWSTR myCaption = L"Caption for the message box";

    MessageBoxW(NULL, myText, myCaption, MB_OKCANCEL);

    return 0;

}
Basic Win32 program for creating a message box
Basic Win32 program for creating a message box

I’ll compile it with mingw-w64’s g++ that we setup in my previous post.

Compiling and running the message box program
Compiling and running the message box program
ws.exe in Explorer
ws.exe in Explorer

All of this might be confusing for people new to the Windows API, so let’s break it down line by line.

 #include <windows.h>

This line tells the g++ compiler to include the “windows.h” header file. Windows.h contains Windows API functions, macros and data types that must be used inside a Win32 application.

 

int WINAPI WinMain

This is the entry point for a graphical Windows application. In simple terms, it’s the equivalent of the standard C++ int main() but specific to Windows GUI applications.

(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)

lpCmdLine contains the command line arguments as a long pointer. nCmdShow decides if the application window will be maximized, minimized or act normally on launch. hPrevInstance is not used these days, its value is NULL or 0. hInstance is a HANDLE to an instance, used to identify the executable when it is loaded into memory. (More info here)

LPCWSTR myText = L"Text for the message box";
LPCWSTR myCaption = L"Caption for the message box";

LPCWSTR is a typedef/alias for const wchar_t * data type. The L prefix before the double quote is used to define a wide character string literal as opposed to a normal string. For more information on Windows data types, look here.

MessageBoxW(NULL, myText, myCaption, MB_OKCANCEL);

MessageBoxW is a Win32 API function used to create a modal dialog box.

int MessageBoxW(
HWND hWnd,
LPCWSTR lpText,
LPCWSTR lpCaption,
UINT uType
);

hWnd is a handle to the owner window of the dialog. Since we don’t have a parent window for our message box, we’ll leave it as NULL.

uType decides the contents and behavior of the dialog box. It can be defined with flags explained here.

Here’s a picture of message boxes with different uType values.

Message Boxes with different uTypes
Message Boxes with different uType values

We can create a composite message box by combining uType flags using the bitwise OR (|) operator. For example,

MessageBoxW(NULL, myText, myCaption, MB_HELP | MB_OKCANCEL);
Message Box with multiple flags
Message Box with multiple flags

Leave a comment