Stopwatch in Visual Basic
Submitted by Yorkiebar on Tuesday, May 13, 2014 - 08:46.
Introduction:
This tutorial is on how to create a simple stopwatch in Visual Basic.
Important:
First we need to import the threading namespace...
We also need to create a global variable to hold whether the stopwatch is currently running or not...
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...
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...
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...
Button, Stop:
The stop button just sets the 'going' variable to false to stop the loop...
- Imports System.Threading
- Dim going As Boolean = False
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- CheckForIllegalCrossThreadCalls = False
- End Sub
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- Dim trd As New Thread(AddressOf Stopwatch)
- trd.IsBackground = True
- going = True
- trd.Start()
- End Sub
- Private Function Stopwatch()
- While (going)
- Dim temp As Integer = Convert.ToInt32(Label1.Text)
- Label1.Text = (temp + 1).ToString()
- Thread.Sleep(1000)
- End While
- End Function
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
- going = False
- End Sub
Add new comment
- 27 views