How to use the mouse in your application

In this tutorial I'm going to explain how you can use the mouse properly in your Visual Basic application. You don't have to know very much about Visual Basic to understand this tutorial, just the basics.

1: Create a new application. First we create the interface. Let's make three labels with the following properties:
Name: lblX, lblY , lblInfo
Caption: X-Coordinate: , Y-Coordinate , Nothing
Width: 1000, 1000, 2000
Height: 500, 500, 2000
Left: 100, 100, 100
Top: 100, 600, 1100
Change the Form1-WindowState property into 2-Maximized.

2: Now we're going to write some code. Add a module and paste the following code into it:

Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long

Public Type POINTAPI
x As Long
y As Long
End Type

Public MousePos As POINTAPI

The function uses a library that puts the coordinates of the mouse on the screen in a type named POINTAPI. This type has only two properties, X and Y that represent the position of the mouse on the X and Y Axis. Next we declare a variable that we use to store the X and Y position.

3: We want to know the position of the mouse constantly, because the user moves the mouse and the position of the mouse changes. So we have to update the variables of MousePos all the time. This can be done with the help of a timer. So, add a timer with an interval of 20 milliseconds and put the following code into the Timer1_Timer event:

GetCursorPos MousePos

This way the mouseposition is updated every 1/50 second.

4: Now we're going to do something with this information. Add the following code to the Timer1_Timer event and paste it below the GetCursorPos MousePos:

lblX.Caption = "X-Coordinate: " & MousePos.x
lblY.Caption = "Y-Coordinate: " & MousePos.y

Every 1/50 second, the information on the labels is updated.

5: The last thing I explain is how to use the right, middle and left mousebutton. Add the following code into the Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) event:

If Button = 1 Then lblInfo.Caption = "You've left-clicked on this position: " & "(" & MousePos.X _
& "," & MousePos.Y & ")"

If Button = 2 Then lblInfo.Caption = "You've right-clicked on this position: " & "(" & MousePos.X _
& "," & MousePos.Y & ")"

If Button = 4 Then lblInfo.Caption = "You've middle-clicked on this position: " & "(" & MousePos.X _
& "," & MousePos.Y & ")"

I think you'll see that Button stands for the leftmousebutton, the rightmousebutton or the middlemousebutton.

That was it! I hope you've learnt something from this tutorial. You can download the application by clicking HERE. If you have any comments or whatever, feel free to sent me an e-mail by clicking HERE.

<-- Back to tutorials