How to Create a Clock in Visual Basic

Language
Introduction: Welcome to a tutorial on how to create a clock in Visual Basic. Steps of Creation: Step 1: I will just be loading the current time in to a simple, plain label. You can customize yours or set it as a filewriter etc. So first we want to set checking for illegal crossThread calls to false on the form load. This is because we will be using a new thread to run the loop of updating the clock and it will be an illegal crossThread call which would throw an error. We also want to begin our function on form load.
  1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.     CheckForIllegalCrossThreadCalls = False
  3.     begin()
  4. End Sub
We also want to import a threading namespace...
  1. Imports System.Threading
Step 2: Next we want to create our begin function. This will create our new thread and set it to the addressOf updateClock, another custom function (which is not yet created). We also set it to background and start it.
  1. Private Function begin()
  2.     Dim trd As thread = New Thread(AddressOf updateClock)
  3.     trd.isBackground = True
  4.     trd.Start()
  5. End Function
Step 3: Finally we create our updateClock function. This simply sets the label1 text with the current time in the format of HourHour:MinuteMinute:SecondsSeconds.
  1. Private Function updateClock()
  2.     While True
  3.         Label1.Text = Format(Now, "hh:mm:ss")
  4.         thread.sleep(1000)
  5.     End While
  6. End Function
Project Complete! Below is the full source code and download to the 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.         begin()
  6.     End Sub
  7.  
  8.     Private Function begin()
  9.         Dim trd As thread = New Thread(AddressOf updateClock)
  10.         trd.isBackground = True
  11.         trd.Start()
  12.     End Function
  13.  
  14.     Private Function updateClock()
  15.         While True
  16.             Label1.Text = Format(Now, "hh:mm:ss")
  17.             thread.sleep(1000)
  18.         End While
  19.     End Function
  20. End Class

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment