17.3 Keyboard Events

When a user presses a key on the keyboard, Windows sends a series of messages to the current active window. These messages include WM_KEYDOWN, WM_KEYUP, and WM_CHAR. The Foundation window classes support these messages with message map entries and message-handler functions, just as it does for other window messages. The keyboard messages and their associated message- map entries and message-handler functions are shown in the following list:

Message Message-map macro Message-handler function

WM_KEYDOWN ON_WM_KEYDOWN OnKeyDown
WM_KEYUP ON_WM_KEYUP OnKeyUp
WM_CHAR ON_WM_CHAR OnChar

·To handle any of these key messages:

1.Derive a window class from an existing Foundation window class

2.Implement the appropriate message-handler functions

3.Define message-map entries for the messages that you want to handle

The following example shows a window class that handles the WM_CHAR message.

First, the class is derived from an existing Foundation window class and the OnChar message-handler function is declared:

class CMainWnd : public CFrameWnd

{

public:

// constructor

CMyWnd()

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

DECLARE_MESSAGE_MAP()

};

Next, the message map for the window class is defined in the .CPP file for the class:

BEGIN_MESSAGE_MAP( CMainWnd, CFrameWnd )

ON_WM_CHAR()

END_MESSAGE_MAP()

Finally, you define the OnChar message-handler function. It has three arguments. The first contains the ASCII code for the character typed on the keyboard, the second contains the repeat count if the message is the result of keyboard autorepeat, and the third contains flags that indicate various other conditions of the keyboard, such as whether or not the ALT key was down when the key was pressed. The following code shows a skeleton for the OnChar function:

void CMainWnd::OnChar( UINT nChar, UINT nRepCnt, UINT nFlags )

{

TRACE( "The %c character was pressed\n", wChar );

}