14.5 Overriding Window Procedure for a Window Class

The preferred way to handle window messages with the Microsoft Foundation Class Library is to use message maps and message-handler functions. You can, however, override the window procedure for a Foundation window class to use the more traditional Windows-style switch statement to respond to window messages.

·To use a traditional window procedure in your derived window class:

1.Override base window class WindowProc.

2.Use a traditional switch statement that uses WindowProc parameters.

3.Call base class WindowProc to get message-map processing for those messages that are not handled directly.

The following example code shows how to override WindowProc for a class derived from CEdit. Like the previous section, this derived class, named CNumEdit, accepts only digits. You can compare the message-map version in the previous section with this more traditional version. The first code fragment is a partial class declaration for CNumEdit, showing the declaration for overriding WindowProc. After that is the implementation of the overriding WindowProc.

class CNumEdit : public CEdit

{

// other declaration stuff left out...

virtual LONG WindowProc( UINT message, UINT wParam, LONG lParam );

// other declaration details left out...

};

LONG CNumEdit::WindowProc( UINT message, UINT wParam, LONG lParam )

{

switch( message )

{

case WM_CHAR:

if( ( wParam <= '9' ) && ( wParam >= '0' ) )

{

return CEdit::WindowProc( message, wParam, lParam );

}

else

{

return FALSE;

}

default:

return CEdit::WindowProc( message, wParam, lParam );

}

}