Processing Messages

A window function receives messages from two sources. Input messages come from the message loop and window-management messages come directly from Windows.

In either case, Windows has a series of constants that define the different types of messages. These constants always start with WM_. For example, a WM_CREATE message is a signal for the program to create a window. WM_KEYDOWN tells the window a key has been pressed. WM_QUIT informs the application it's time to terminate. You write your own code to handle the various messages Windows sends that are applicable to your program.

The most common way to handle messages inside the window function is with a switch statement:

unsigned message;

.

.

.

switch (message)

{

case WM_COMMAND:

{

.

. /* process command from application menu */

.

}

case WM_DESTROY:

PostQuitMessage(0);

break;

default:

return (DefWindowProc(hWnd, message, wParam, lParam));

}

The window function is repeatedly passed messages for the switch statement to process.

Whenever the user chooses a menu command, Windows generates a WM_COMMAND message along with the identification number of the chosen command. If your Windows program has menus, always check for a WM_COMMAND message. Your code should have a nested switch or if-else statement to check for the menu ID and run the code associated with it.

When a window is destroyed (closed), Windows sends the WM_DESTROY message to the window function immediately after destroying the window. This gives the window function a chance to finish its processing. In this case, when the window is destroyed, the program quits. PostQuitMessage is called after the window is destroyed. This places a WM_QUIT message in the program queue, causing the GetMessage message loop and the program to terminate.

If you don't process the message, always pass it back to Windows with the DefWindowProc function for default processing. This ensures that any special actions that affect the window, program, or Windows itself are carried out.

See the “Creating Windows Programs” section for additional information on Windows messages and flow control.