Visual Basic Concepts

Using Button to Enhance Graphical Mouse Applications

See Also

You can use the button argument to enhance the Scribble application described in "The MouseMove Event" earlier in this chapter. In addition to drawing a continuous line when the left mouse button is pressed and stopping when the button is released, the application can draw a straight line from the last point drawn when the user presses the right button.

When writing code, it is often helpful to note each relevant event and the desired response. The three relevant events here are the mouse events:

The variable DrawNow is declared in the Declarations section of the form:

Dim DrawNow As Boolean

The MouseDown procedure has to take a different action, depending on whether the left or right mouse button caused the event:

Private Sub Form_MouseDown (Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   If Button = vbLeftButton Then
      DrawNow = True
      CurrentX = X
      CurrentY = Y
   ElseIf Button = vbRightButton Then
      Line -(X, Y)
   End If
End Sub

The following MouseUp procedure turns off drawing only when the left button is released:

Private Sub Form_MouseUp (Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   If Button = vbLeftButton Then DrawNow = False
End Sub

Note that within the MouseUp procedure, a bit set to 1 (vbLeftButton) indicates that the corresponding mouse button is released and drawing is turned off.

The following MouseMove procedure is identical to the one in the version of the Scribble application found in "The MouseMove Event" earlier in this chapter.

Private Sub Form_MouseMove (Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   If DrawNow Then Line -(X, Y)
End Sub