Timer in Visual Basic

Introduction: This tutorial is on how to create a timer in Visual Basic. Threads: Te first thing you must know about this tutorial is how to use threads. Threads are essentially processes which run certain parts of your programs code, the main thread handles the design of your form as well as the code of your form, therefore, when you have a lot of long-running code, your UI will freeze. We can get around this by using additional threads. Design: For this we simply need one label on a new Windows Form and a numericupdown number box. We also want a button to begin the timer. Imports: For threading, we need to import the threading namespace...
  1. Imports System.Threading
Button Click: Once the button is clicked, we first want to create a new thread to run the timer....
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2. Dim trd As New thread(AddressOf timing)
  3. trd.isbackground = True
  4. trd.start()
  5. End Sub
we then want to create a variable to hold the current timer time and set the value to the numericupdown value (seconds)...
  1. Private Function timing()
  2. Dim timeing As Integer = NumericUpDown1.Value
  3. End Function
Next we want to loop around through each unit of the numericupdown value, each loop we want to reduce the variable value by one, and re-set the label to the value of the timer, as a string...
  1. Private Function timing()
  2. Dim timeing As Integer = NumericUpDown1.Value
  3. For i As Integer = 0 To timeing
  4. Label1.Text = (timeing - i).ToString() + "Seconds..."
  5. Thread.Sleep(1000)
  6. Next
  7. MsgBox("Timer Done")
  8. End Function
Cross Threading: The final thing we need to do is disable checking for illegal cross thread calls otherwise we will get an error when trying to access the label control from a newly created thread (trd)...
  1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2. CheckForIllegalCrossThreadCalls = False
  3. End Sub

Add new comment