How to Create a Mouse Position Tool in Visual Basic

Language: 

Introduction:
Welcome to my tutorial on how to create a Mouse Position tool in Visual Basic. This is easy so I will also be explaining Threading.

Steps of Creation:
Step 1:

First we need to import System.Threading so we can use Threads. We also want to create a form with just a label, this will contain our mouse position.

  1. Imports System.Threading

Step 2:
Now we want to create and initiate a Thread on form load...

  1. CheckForIllegalCrossThreadCalls = False
  2. Dim trd As Thread = New Thread(AddressOf begin)
  3. trd.isBackground = True
  4. trd.Start()

We also stop checking for illegal cross thread calls because if we don't, it will throw an error when trying to access the label1 control from a new thread because the control was created on the main thread.

Step 3:
Now we want to create our begin function which the new Thread starts on. We want it to update our label text with the mouse position so we put it in a constant loop.

  1. Private Function begin()
  2. Do While True
  3. Label1.Text = "X: " & MousePosition.X & ", Y: " & MousePosition.Y
  4. Loop
  5. End Function

Step 4:
Finally, we want to add in a 0.1 second sleep between each loop of updating our label so it doesn't overuse resources from our computer etc.

  1. Thread.Sleep(100)

Project Complete!
Below is the full source code and download to the project files.

  1. Imports System.Threading
  2. Public Class Form1
  3. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  4. CheckForIllegalCrossThreadCalls = False
  5. Dim trd As Thread = New Thread(AddressOf begin)
  6. trd.isBackground = True
  7. trd.Start()
  8. End Sub
  9.  
  10. Private Function begin()
  11. Do While True
  12. Label1.Text = "X: " & MousePosition.X & ", Y: " & MousePosition.Y
  13. Thread.Sleep(100)
  14. Loop
  15. End Function
  16. End Class

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.

Filtered HTML

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <csharp>, <css>, <java>, <javascript>, <php>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
To prevent automated spam submissions leave this field empty.