14.4 Calling the Default Window Procedure from a Message-Handler Function

A common practice in Windows programming is to handle a particular window message in a window procedure and then call the default window procedure, DefWindowProc, to finish the processing for the message. If you are using the Microsoft Foundation Class Library's message-map mechanism to handle window messages, you call your base class's message-handler function if you want to finish processing the message in the default manner. You should not change the arguments to the message handler before passing them on to the base class message handler.

The following example shows how a derived class might handle a WM_CHAR message under certain circumstances and pass the message on to its base class for further processing as necessary.

·To filter keystrokes to a CEdit control, allowing only digits:

1.Derive a class from CEdit and define the OnChar message-handler function to handle WM_CHAR messages.

2.For each WM_CHAR message, add code to examine the incoming character to see if it is a digit.

If the character is a digit, call the base class version of OnChar to allow the character to be inserted into the control in the default way. You can also allow the BACKSPACE key and TAB keys to be processed in the default manner.

If the character isn't a digit, simply return without calling the base class OnChar. This will cause the character to be ignored by the control.

The following class declaration shows how this might be done:

class CNumEdit : public CEdit

{

public:

afx_msg void OnChar( UINT nChar, UINT nRepCnt, UINT nFlags )

{

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

|| ( nChar == VK_TAB )

|| ( nChar == VK_BACK ))

{

CEdit::OnChar( nChar, nRepCnt, nFlags );

}

}

DECLARE_MESSAGE_MAP()

};

BEGIN_MESSAGE_MAP( CNumEdit, CEdit )

ON_WM_CHAR()

END_MESSAGE_MAP()

For a more complete discussion of the CNumEdit example shown above, see “Deriving Controls from a Standard Control” on page 337.