Loading

Win32: Responding to Mouse Clicks

Responding to Mouse Clicks

In this tutorial, we demonstrate how to write code to respond to a mouse-click event. Specifically, we show how to respond to mouse-button-down events, but other mouse events are very similar. Mouse-click events happen when the user clicks inside of the client area of the window (outlined in green below).

We begin with the code from Win32 Lesson 1, and add the following left-mouse-button-down handler at line 143 of the file "Win32lesson1.cpp:"

case WM_LBUTTONDOWN:
{
    int iPosX = LOWORD(lParam);
    int iPosY = HIWORD(lParam);
    wchar_t waCoord[20];
    wsprintf(waCoord, _T("(%i, %i)"), iPosX, iPosY);
    ::MessageBox(hWnd, waCoord, _T("LMB Click"), MB_OK);
    break;
}

The code above is executed after the left mouse button is pressed and the message is processed from the message queue. The first two line extract the coordinates of the button press by taking the lower 16 bits for the x-coordinate and the higher 16 bits for the y-coordinate. Using the wsprintf() function we create string with our coordinates in it, which we then pass in to the message box function.

After adding the code above and executing the program, we can click inside the client area of the window and we will see a message box pop up, like the one shown above. Our message box has a coordinates displayed inside the message box and the text "LMB Click" in the title bar to tell us what type of event has occurred. We have used a simple "OK" button for the message box style.

We can respond to right-mouse-button-down events just like we respond to left-mouse-button-down events. Add the following code at line 152 of the file "Win32lesson1.cpp:"

case WM_RBUTTONDOWN:
{
    int iPosX = LOWORD(lParam);
    int iPosY = HIWORD(lParam);
    wchar_t waCoord[20];
    wsprintf(waCoord, _T("(%i, %i)"), iPosX, iPosY);
    ::MessageBox(hWnd, waCoord, _T("RMB Click"), MB_OK);
    break;
}

Now, if we compile and execute the program we can click either the left or right mouse button to pop up a message box with the coordinates. The message box for right-mouse-button clicks is shown above.

Shown here is a list of mouse button events that we can respond to. This code is located in "WinUser.h" and shows the defined message types. As we did above, we can write handlers to respond to left-mouse-button-up events, for example, just as we did for left-mouse-button-down events.