Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Visual C++ and MFC Fundamentals Chapter 12: Dialog-Based Windows


Once a message has been decoded, the application must send it to the window procedure.
This is done using the DispatchMessage() function. Its syntax is:

LRESULT DispatchMessage(CONST MSG *lpMsg);

This function also takes as argument the MSG object that was passed to GetMessage()
and analyzed by TranslateMessage(). This DispatchMessage() function sends the lpMsg
message to the window procedure. The window procedure processes it and sends back
the result, which becomes the return value of this function. Normally, when the window
procedure receives the message, it establishes a relationship with the control that sent the
message and starts treating it. By the time the window procedure finishes with the
message, the issue is resolved (or aborted). This means that, by the time the window
procedure returns its result, the message is not an issue anymore. For this reason you will
usually, if ever, not need to retrieve the result of the DispatchMessage() function.

This translating and dispatching of messages is an on-going process that goes on as long
as your application is running and as long as somebody is using it. For this reason, the
application uses a while loop to continuously check new messages. This behavior can be
implemented as follows:

while( GetMessage(&Msg, NULL, 0, 0) )
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}

If the WinMain() function successfully creates the application and the window, it returns
the wParam value of the MSG used on the application.

Practical Learning: Completing the Application



  1. To finalize the application, complete it as follows:


#include <windows.h>
//---------------------------------------------------------------------------
char StrClassName[] = "Win32Exercise";
char StrWndName[] = "Simple Win32 Application";
//---------------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg,
WPARAM wParam, LPARAM lParam);
//---------------------------------------------------------------------------
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow )
{
MSG Msg;
HWND hWnd;
WNDCLASSEX WndClsEx;

WndClsEx.cbSize = sizeof(WNDCLASSEX);
WndClsEx.style = CS_HREDRAW | CS_VREDRAW;
WndClsEx.lpfnWndProc = WndProc;
WndClsEx.cbClsExtra = 0;
WndClsEx.cbWndExtra = 0;
WndClsEx.hInstance = hInstance;
WndClsEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
WndClsEx.hCursor = LoadCursor(NULL, IDC_CROSS);
WndClsEx.hbrBackground = (HBRUSH)( COLOR_BACKGROUND + 1);
Free download pdf