Discussion: Keyboard and Mouse Message Handlers

This section explains the keyboard and mouse message-handler member functions.

OnUp and OnDown

The Phone Book window contains lines of text, each line representing one person's data. For some actions, such as deleting or editing a person, the user must “select” a person—by selecting a line in the window—before giving a menu command. Figure 6.5 shows the display with a person selected.

There are several ways to select a person for an action. One way is to press the UP ARROW or DOWN ARROW keys. The UP ARROW moves the selection up a line. If the selection was already on the first person in the database, UP wraps the selection down to the last person in the database. The DOWN ARROW moves the selection down a line and wraps to the top. Double-clicking a line in the display both selects the person and invokes the main window object's OnEdit member function for it.

When the Phone Book window receives an ON_COMMAND message containing the ID number of either of these keys (VK_UP and VK_DOWN), the message map calls the main window object's OnUp or OnDown message handler.

OnUp decrements the line number of the current selection. OnDown increments it. Both functions also call a utility member function, InvalidateLine to calculate what part of the display must be repainted and to invalidate that area.

OnLButtonDown and OnLButtonDblClk

When the user presses the left mouse button over the display, the message map converts the WM_LBUTTONDOWN message into a call to OnLButtonDown. When the user double-clicks a line in the display, the message map converts the WM_LBUTTONDBLCLK message into a call to OnLButtonDblClk.

OnLButtonDown works somewhat like the keyboard handlers. It first invalidates the rectangle containing the currently selected line, if any. Then it calculates whether the point at which the mouse was clicked is within the range of the list of persons. If so, it sets the new selection to the line whose rectangle contains that point and invalidates the rectangle. The function causes an update so the window will be repainted with the new selection highlighted.

Similarly, when the user double-clicks the left mouse button, the window object's OnLButtonDblClk member function processes a double click in the display. If the mouse click location was in a line of text representing a person's data, OnLButtonDblClk invokes the OnEdit message-handler function just as if the person had been selected and then that menu command chosen.

Generally a WM_LBUTTONDOWN message precedes a WM_LBUTTONDBLCLK message, so that OnLButtonDown is called to select the database record. The subsequent WM_LBUTTONDLBLCLK message causes the OnLButtonDblClk member function to be called. It calls OnEdit.

Note:

The default window style is WS_DBLCLICK, which ensures that the double-click message is sent by Windows.