Friday, November 4, 2011

Reacting to Messages in C programming

As we saw in the previous section, for every message picked up from the message queue the control is transferred to the WndProc( ) function. This function is shown below:
LRESULT CALLBACK WndProc ( HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam )
This function always receives four parameters. The first parameter is the handle to the window for which the message has been received. The second parameter is the message id, whereas, the third and fourth parameters contain additional information about the message.
LRESULT is a typedef of a long int and represents the return value of this function. CALLBACK is a typedef of __stdcall. This typedef has been done in ‘windows.h’. CALLBACK indicates that the WndProc function has been registered with Windows (through WNDCLASSEX structure in InitInstance( ) ) with an intention that Windows would call this back (through DispatchMessage( ) function).
In the WndProc( ) function we have checked the message id using a switch. If the id is WM_DESTROY then we have called the function OnDestroy( ). This message is posted to the message queue when the user clicks on the ‘Close Window’ button in the title bar. In OnDestroy( ) function we have called the API function PostQuitMessage( ). This function posts a WM_QUIT message into the message queue. As we saw earlier, when this message is picked up the message loop and WinMain( ) is terminated.
For all messages other than WM_DESTROY the control lands in the default clause of switch. Here we have simply made a call to DefWindowProc( ) API function. This function does the default

processing of the message that we have decided not to tackle. The default processing for different message would be different. For example on double clicking the title bar DefWindowProc( ) maximizes the window.
Actually speaking when we close the window a WM_CLOSE message is posted into the message queue. Since we have not handled this message the DefWindowProc( ) function gets called to tackle this message. The DefWindowProc( ) function destroys the window and places a WM_DESTROY message in the message queue. As discussed earlier, in WndProc( ) we have made the provision to terminate the application on encountering WM_DESTROY.
That brings us to the end of a lonnngggg explanation! You can now heave a sigh of relief. I would urge you to go through the above explanation till the time you are absolutely sure that you have understood every detail of it. A very clear understanding of it would help you make a good Windows programmer. For your convenience I have given a flowchart of the entire working in




No comments:

Post a Comment