The Windows operating system is fundamentally a message-driven environment. Applications and system components communicate with each other by sending and receiving messages. Understanding how messages work is crucial for developing robust and responsive Windows applications.
A message is a 32-bit or 64-bit value that represents an event or a command. It is the primary mechanism by which the operating system notifies an application of changes in its environment, such as keyboard input, mouse movements, or timer expirations. Applications also use messages to communicate with each other and with the system.
Each message consists of several components:
HWND
): Identifies the window or control that is the destination of the message.UINT
): A value that specifies the type of message being sent. Windows defines hundreds of standard message codes (e.g., WM_PAINT
, WM_KEYDOWN
, WM_SIZE
).WPARAM
): A message-specific parameter that is typically used for small data values.LPARAM
): Another message-specific parameter that can carry larger data values or pointers to data structures.These components are often bundled within a MSG
structure:
typedef struct tagMSG {
HWND hwnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt;
DWORD lPrivate;
} MSG, *PMSG, NEAR *NPMSG, FAR* LPMSG;
Every Windows application has a message loop. This loop is the heart of the application's responsiveness. It continuously retrieves messages from the system's message queue and dispatches them to the appropriate window procedure for processing.
A typical message loop looks like this:
MSG msg;
BOOL bRet;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0 )
{
if (bRet == -1) // Handle error
{
// Error handling code
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
GetMessage
: Retrieves the next message from the application's message queue. If the queue is empty, it waits until a message arrives.TranslateMessage
: Translates virtual-key messages into character messages.DispatchMessage
: Sends the message to the window procedure associated with the message's destination window.WNDPROC
)Each window in a Windows application has an associated window procedure, a callback function that handles messages directed to that window. The window procedure is responsible for interpreting the message code and performing the appropriate action.
WM_KEYDOWN
, WM_KEYUP
, WM_LBUTTONDOWN
, WM_MOUSEMOVE
, etc.WM_PAINT
(for repainting a window), WM_SIZE
(when a window is resized), WM_DESTROY
(when a window is being closed).It's important for your window procedure to handle relevant messages. If a message is not handled, it should be passed to the default window procedure using DefWindowProc
to ensure proper default behavior.
DispatchMessage
is called, the window procedure executes immediately.