
Originally Posted by
dbasnett
Use both ideas. The StopWatch object to keep track of the time, and the Timer to update the display. Your buttons would manipulate them as needed.
Since were on the subject, Why is milliseconds returned as 3 digits and not two digits?
(see Function FormatSW).
Code:
Public Class Form1
Dim sw As New Stopwatch
' // Return stopwatch elapsed time as "hh:mm:ss:ms" //
Private Function FormatSW(ByVal sw As Stopwatch) As String
With sw.Elapsed
Return .Hours.ToString("00") _
& ":" & .Minutes.ToString("00") _
& ":" & .Seconds.ToString("00") _
& "." & .Milliseconds.ToString("00") '< ms is shown as 3 digits, Why not 2 digits?
End With
End Function
' // Form Load - Setup //
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
TmrDisplay.Stop() ' display timer off
TmrDisplay.Interval = 200 ' display timer speed
LblElapsed.Text = "00:00:00:00" ' label default
' disable pause/stop buttons
BtnPause.Enabled = False
BtnStop.Enabled = False
End Sub
' // start/restart button //
Private Sub BtnStart_Click(sender As System.Object, e As System.EventArgs) Handles BtnStart.Click
' stop display timer
TmrDisplay.Stop()
'reset pause button color
BtnPause.BackColor = SystemColors.Control
' enable pause/stop buttons
BtnPause.Enabled = True
BtnStop.Enabled = True
' reset stopwatch
sw.Restart()
' reset label
LblElapsed.Text = "00:00:00:00"
' start display timer
TmrDisplay.Start()
End Sub
' // stop button //
Private Sub BtnStop_Click(sender As System.Object, e As System.EventArgs) Handles BtnStop.Click
' stop stopwatch, timer
sw.Stop()
TmrDisplay.Stop()
'reset pause button color
BtnPause.BackColor = SystemColors.Control
' disable pause/stop buttons
BtnPause.Enabled = False
BtnStop.Enabled = False
End Sub
' // pause button //
Private Sub BtnPause_Click(sender As System.Object, e As System.EventArgs) Handles BtnPause.Click
'toggle display timer
TmrDisplay.Enabled = Not TmrDisplay.Enabled
If TmrDisplay.Enabled = False Then
' pause stopwatch
sw.Stop()
' set pause button to red
BtnPause.BackColor = Color.Red
Else
' resume stopwatch
sw.Start()
' upate label with elapsed time
LblElapsed.Text = FormatSW(sw)
'reset pause button color
BtnPause.BackColor = SystemColors.Control
End If
End Sub
' // Timer - display //
Private Sub TmrDisplay_Tick(sender As System.Object, e As System.EventArgs) Handles TmrDisplay.Tick
LblElapsed.Text = FormatSW(sw) ' upate label with elapsed sw time
End Sub
End Class