Wyo VB Lecture Notes
Objective #1: Be able to use various Mouse events.
- A MouseClick event
occurs when the user clicks the mouse. The
following method displays the coordinates of where the mouse was clicked
Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Handles Me.MouseClick
If (e.Button = Windows.Forms.MouseButtons.Left) Then
MessageBox.Show("The mouse was clicked at (" + e.X.ToString + ", " +
e.Y.ToString + ")")
End If
End Sub
- A MouseMove event
occurs when the mouse's position changes. The following method displays the
coordinates of the mouse in two labels
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Handles MyBase.MouseMove
lblX.Text = e.X
lblY.Text = e.Y
End Sub
The following code segment goes even further to allow the user to drag a picture box around the screen and detects a collision with a line segment:
' move player around screen with mouse
Private Sub Form1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
picPlayer.Left = e.X - picPlayer.Width / 2
picPlayer.Top = e.Y - picPlayer.Height / 2
' Can you explain why the statement above is
' better than the shorter statement: picPlayer.Top = e.Y
If (picPlayer.Left < 200 And picPlayer.Right > 200 And picPlayer.Top < 150 And picPlayer.Bottom > 100) Then
MessageBox.Show("collision")
End If
End Sub
' draw maze
Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
e.Graphics.DrawLine(Pens.Black, 200, 100, 200, 150)
End Sub
- A MouseDown event
occurs when the user presses the mouse button somewhere on the form. The
following method displays the coordinates of where the mouse was clicked
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Handles MyBase.MouseDown
If (e.Button = Windows.Forms.MouseButtons.Left) Then
MessageBox.Show("The mouse was clicked at (" + e.X.ToString + ", " +
e.Y.ToString + ")")
End If
End Sub
- A MouseUp event
occurs when the user releases the mouse button. Note that the MouseUp event
may occur in the very next instant after its corresponding MouseDown event
if the user clicked the mouse quickly. Or, if the user decides to hold down
the mouse button for a long time or he/she drags the mouse across the screen,
the MouseUp event will occur much later than its corresponding MouseDown event.