• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

VB Guide, Working with Timers and Stopwatch

Joined
Dec 13, 2007
Messages
2,758 (0.46/day)
This will show you how to make time counter and show real time.

In order of things that happen

On Load: Label text becomes the Date/Time when loaded
Button Click: Timer and Stopwatch has started
Timer: The code will run ever 1sec.
First label will show the counter starting from zero. Showing Hours/Mins/Secs
Second label will update the time (This is the time set on your computer)
Once stopwatch has reach 30secs, Timer will stop. And a message box will appear

That's It!

Code:
Imports System.Threading
Imports System.Diagnostics
Public Class Main
    Private Watch As New System.Diagnostics.Stopwatch
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Starting Timer
        Timer1.Start()

        'Starting Watch
        Watch.Start()
    End Sub
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Since working with time, setting 1000(ms) is 1sec. 
        Timer1.Interval = 1000

        'Hours/Mins/Secs
        Label2.Text = Watch.Elapsed.Hours.ToString & "hr" & Space(1) & Watch.Elapsed.Minutes.ToString & "min" & Space(1) & Watch.Elapsed.Seconds.ToString & "sec"

        'Date/Time
        Label3.Text = Date.Now

        'Stop Timer at 30secs, and pop up a messagebox
        If Watch.Elapsed.Seconds = "30" Then
            Timer1.Stop()
            MsgBox("Timer Stop")
        End If
    End Sub
    Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Set Label to Now Date/Time of Load
        Label3.Text = Date.Now
    End Sub
End Class

On Load:


What happens at 30secs:



*Note
If you want to change the "30secs" to your liking
Code:
If Watch.Elapsed.Seconds = "Enter Your Value Here" Then

With Stopwatch you gather Elapsed Days/Hours/Mins/Seconds/MilliSeconds/Secs/Ticks or Total Days/Hours/Mins/Seconds/MilliSeconds/Secs/Ticks

Elapsed Example
Code:
Watch.Elapsed.Seconds.ToString

Total Example
Code:
Watch.Elapsed.TotalSeconds.ToString

Need code in C#... Try using Developer Fusion Converter
 
Top