Win32 Tutorials


Mouse Input

Tutorials > Win32 > Mouse Input

View Full Source


In the previous tutorial, we discussed how to record input from the keyboard. This tutorial will explain how to accept mouse messages.

Contents of main.cpp :

First we look at the WM_LBUTTONDOWN message. There is also a WM_RBUTTONDOWN equivalent. This is obviously sent when you left-click or right-click the mouse button. Below, a message is displayed when the left mouse button is clicked.

	    MessageBox(hwnd, "L Mouse Down", "Mouse", MB_OK);

Next we look at the WM_RBUTTONDBLCLK message. Once again there is a left button equivalent. This message occurs when you double click a button.

For this to work, you need to add the CS_DBLCLKS style to the window class. ie. = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;

Our double click message handler is shown below. A message is displayed when the right mouse button is double-clicked.

	    MessageBox(hwnd, "Double Click", "Mouse", MB_OK);

Next we will discuss the WM_MOUSEMOVE message. This message is sent everytime the mouse is moved within the window.


2 macros are available to retrieve the high order and low order word of a variable. Sometimes multiple pieces of data are stored in one variable. These can be retrieved by using the LOWORD and HIWORD macros. An example of this is the lParam parameter for all mouse messages.

The x coordinate of the mouse at the time of the message is given by LOWORD(lParam) and the y coordinate is given by HIWORD(lParam). The coordinates can be retrieved in both messages above as well.

	        int x = LOWORD(lParam);
	        int y = HIWORD(lParam);

The wParam variable holds any other keys or buttons that could have been down when the mouse event occurred. You can use the & (and) operator with the key or button flag to determine if the key or button is down. If the key or button is down, a non NULL return value will be given.

The key or button flags start with MK_* eg. MK_LBUTTON, MK_MBUTTON, MK_SHIFT, MK_CONTROL, etc.

Below we check if the right hand mouse button is down while the mouse is moving.

	        if (wParam & MK_RBUTTON)

If it is, we display the coordinates of the mouse at the time of the event.

	            char text[50];
	            sprintf(text, "%d %d", x, y);

	            MessageBox(hwnd, text, "Mouse", MB_OK);

If you run the program, you will be presented with a window. If you left-click in the window, a message box will be displayed. If you double right-click on the window, you will receive a message box and if you hold the right mouse button down while moving the mouse, you will receive a message box showing the coordinates of the mouse.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++

< Tutorial 07 - Keyboard Input  

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer