17.1 Handling a Mouse Click in a Window

To handle a mouse click in your window, you need to handle the WM_LBUTTONDOWN or WM_RBUTTONDOWN message. Using the Microsoft Foundation classes mechanism for handling messages, you will find the following three steps necessary to handle mouse-click messages:

1.Derive your window class from an existing Foundation window class (such as CFrameWnd or CMDIChildWnd).

2.Define the OnLButtonDown or OnRButtonDown message-handler member functions for your window class, depending on whether you want to handle left or right mouse button events.

3.Define-message map entries using the ON_WM_LBUTTONDOWN or ON_WM_RBUTTONDOWN macros, depending on whether you want to handle left or right mouse button events.

The following class declaration fragment shows how to declare the OnLButtonDown function in a derived window class. It also shows the necessary inclusion of the DECLARE_MESSAGE_MAP macro to enable the message-map mechanism for the derived class.

class CMainWnd : public CFrameWnd

{

// other declaration stuff left out...

// declare message-handler function

afx_msg void OnLButtonDown( UINT nFlags, CPoint point );

DECLARE_MESSAGE_MAP()

};

The OnLButtonDown message-handler function has two arguments; a UINT which indicates whether the CONTROL and/or SHIFT keys were pressed when the mouse was clicked, and a CPoint argument containing the coordinates of the mouse at the time of the click. The following function definition shows how to look at the information in these arguments.

void CMainWnd::OnLButtonDown(UINT nFlags, CPoint point)

{

TRACE("LBUTTON down message, point = %d , %d\n",point.x,point.y);

if(nFlags & MK_CONTROL)

TRACE("Control key was down\n");

if(nFlags & MK_SHIFT)

TRACE("Shift key was down\n");

}

The definition of the message-map entries for the mouse down messages is the same as described for other messages elsewhere in this documentation. The following example shows how to define a message-map entry for the WM_LBUTTONDOWN message for the derived window class described in this section.

// in .CPP file

BEGIN_MESSAGE_MAP( CMainWnd, CFrameWnd )

ON_WM_LBUTTONDOWN()

END_MESSAGE_MAP()

Note:

You can handle the WM_RBUTTONDBLCLK or WM_LBUTTONDBLCLK messages for double clicks in your window.