February 26, 2001

HOW MESSAGES ARE PROCESSED in MFC/Windows?

From my notes..

HOW MESSAGES ARE PROCESSED in MFC/Windows?

With the help of the Class Wizard’s help we write handler functions for various Windows messages.

Eg., OnDraw() function is executed when WM_PAINT message is generated.

Messages are handled by MFC code which look like this below :

// Message Handling Code :
MFG message; while (::GetMessage(&message,NULL,0,0))
{
::TranslateMessage(&message);
::DispatchMessage(&message);
}

The above figure shows that a system queue is maintained
1. The Queue ie., Windows OS determines which messages belong to the program.
2. GetMessage function returns when a message needs to be processed.
3. When messages are posted, TranslateMessage will translate the messages. ie., for example WM_KEYDOWN message is translated into WM_CHAR messages containing ASCII characters.
4. DespatchMessage function passes the control to the handler function via the Message map.
5. Once the Handler function is finished, it returns to the MFC code which written above.


MESSAGE_MAP :

1. A Message Map is basically a router to direct the message to a message’s handler function when a message is received in the program.
2. Once the message is handled then the control is given back to the OS to get the next message.
3. Routing a message to an individual handler function is done by the message map.
4. The Message map specifies which function is called for each message.
5. It also lets the message to pass to the Windows default message processing logic.
6. Several Macros declared in <afxwin.h > are used to create Message Map.
7. The macro will be present in all the classes which the handles the messages.
8. All the header files of the classes which handle messages will have the following macro declaration.

DECLARE_MESSAGE_MAP()

Conventionally we say that the above is declared at the end of the class.

Eg.,
class xxxxx
{
DECLARE_MESSAGE_MAP()
};



In the Implementation file, ( ie., *.cpp ) there will be a table which will be defined.
The table will be starting with the following :

BEGIN_MESSAGE_MAP( .. .. ) ----> 1

This defines the class name that is handled by this message map and the parent class name when unhandled messages are passed.

So, there will 2 arguments which will be supplied to the BEGIN_MESSAGE_MAP( <class name>,<base class name>).

The table will be Ending with the following:

END_MESSAGE_MAP() -----> 2

Between above two massage map entries (1 & 2) there will be number of references to messages which can be processed by the program.