Stopwatch in Visual Basic

Introduction: This tutorial is on how to create a simple stopwatch in Visual Basic. Important: First we need to import the threading namespace...
  1. Imports System.Threading
We also need to create a global variable to hold whether the stopwatch is currently running or not...
  1. Dim going As Boolean = False
Please set the default text of the label, to '0' or another numeric value, otherwise it will crash on converting the text to an integer. Design: The Windows Form requires three components; Label, label1, to hold the current amount of seconds on the stopwatch. Button, button1, to start the stopwatch. Button, button2, to stop the stopwatch. Form Load: Because we are using multiple threads, we need to disable CheckForIllegaCrossThreadCalls on form load/application start-up otherwise we would get an error when trying to access any components on the form from anything other than the main thread which created it...
  1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.     CheckForIllegalCrossThreadCalls = False
  3. End Sub
Button, Start: For the starting button, we simply create a new thread, set it to run a 'stopwatch' function, give it the background property as true, set our 'going' variable as true and start the thread...
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2.         Dim trd As New Thread(AddressOf Stopwatch)
  3.         trd.IsBackground = True
  4.         going = True
  5.         trd.Start()
  6. End Sub
Stopwatch Function: The stopwatch function simply runs while the 'going' variable is true (stopwatch is active/running). For each run, it gets the current label text as an integer, then re-sets the label text to the integer received before, plus one. It then waits 1000ms (1 second) and does it again, unless the boolean 'going' is set to false...
  1. Private Function Stopwatch()
  2.         While (going)
  3.                 Dim temp As Integer = Convert.ToInt32(Label1.Text)
  4.                 Label1.Text = (temp + 1).ToString()
  5.                 Thread.Sleep(1000)
  6.         End While
  7. End Function
Button, Stop: The stop button just sets the 'going' variable to false to stop the loop...
  1. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  2.     going = False
  3. End Sub

Add new comment