Share via


Visual Basic Concepts

Detecting Mouse Buttons

You can make your applications more powerful by writing code that responds differently to mouse events, depending on which mouse button is used or whether the SHIFT, CTRL, or ALT key is pressed. To provide these options, you use the arguments button and shift with the MouseDown, MouseUp, and MouseMove event procedures. Techniques for using the shift argument are described in "Detecting SHIFT, CTRL , and ALT States" later in this chapter.

The MouseDown, MouseUp, and MouseMove events use the button argument to determine which mouse button or buttons are pressed. The button argument is a bit-field argument — a value in which each bit represents a state or condition. These values are expressed as integers. The three least-significant (lowest) bits represent the left, right, and middle mouse buttons, as shown in Figure 11.4.

Figure 11.4   How bits represent the state of the mouse

The default value of each bit is 0 (False). If no buttons are pressed, the binary value of the three bits is 000. If you press the left button, the binary value, or pattern, changes to 001. The left-button bit-value changes from 0 (False) to 1 (True).

The button argument uses either a decimal value or an constant to represent these binary patterns. The following table lists the binary value of the bits, the decimal equivalent, and the Visual Basic constant:

Binary Value Decimal Value Constant Meaning
001 1 vbLeftButton The left button is pressed.
010 2 vbRightButton The right button is pressed.
100 4 vbMiddleButton The middle button is pressed.

Note   Visual Basic provides constants that represent the binary values of the button and shift arguments. These constants can be used interchangeably with their equivalent decimal values. Not all values have corresponding constants, however. The values for some button and/or shift combinations are derived by simply adding decimal values.

The middle button is assigned to decimal value 4. Pressing the left and right buttons simultaneously produces a single digit value of 3 (1+2). On a three-button mouse, pressing all three buttons simultaneously produces the decimal value of 7 (4+2+1). The following table lists the remaining button values derived from the possible button combinations:

Binary Value Decimal Value Constant Meaning
000 0   No buttons are pressed.
011 3 vbLeftButton + vbRightButton The left and right buttons are pressed.
101 5 vbLeftButton + vbMiddleButton The left and middle buttons are pressed.
110 6 vbRightButton + vbMiddleButton The right and middle buttons are pressed.
111 7 vbRightButton + vbMiddleButton + vbLeftButton All three buttons are pressed.