VB.NET – Mouse Events

This post was written by Brandon on December 10, 2008
Posted Under: Visual Basics .NET

I figured a little tutorial on mouse events in VB will be helpful!

There are two methods, mouse down and mouse up. Mouse down handles clicking on the form, and basically doing things while the mouse button is being held down. Mouse up does the opposite, handles doing things when the mouse is not being clicked, or detecting where it was unclicked.

Here is the mouse down event:

Private Sub Form1_Mousedown(ByVal sender As System.Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
'do stuff
End If
End Sub

With this you can do various things. Instead of MouseButtons.Left you can also use MouseButtons.Right and MouseButtons.Middle. Also, you can determine where the mouse was clicked by using e.X and e.Y.

For example, add this line of code into your mouseDown method and click on the form:

If e.Button = MouseButtons.Left Then
MessageBox.Show("Left mouse button clicked at: " & e.X & ", " & e.Y)
Else If e.Button = Mousebuttons.Middle Then
MessageBox.Show("Middle mouse button clicked at: " & e.X & ", " & e.Y)
Else If e.Button = Mousebuttons.Right Then
MessageBox.Show("Right mouse button clicked at: " & e.X & ", " & e.Y)
End If

Easy enough? MouseUp is the exact same thing...

Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then

End If
End Sub

This allows you to do all the same functions.

What can it be used for? Well when the mouse is clicked, you can set a boolean to true, and when its released you can set it back to false. Then you can have a Timer to check when the mouse is being held down and do something. In the project file from my previous post, VB.NET - Handling shape movements and collision, it is used for growth of the shapes. When the "helddown" boolean is true, the size of the current rectangle is continuously increased by 1 until the mouse is released.

Thats all for that!

Add a Comment

required, use real name
required, will not be published
optional, your blog address