【发布时间】:2019-10-01 00:57:41
【问题描述】:
目前我正在尝试在 Visual Basic 中创建一个需要启动、恢复/暂停和停止方法的计时器。但是当我添加停止方法时,计时器确实停止但没有重置计时器的值。有时当我尝试再次启动它时,计时器会滴答作响(例如:-15:-44:-12)。你能帮我么?任何帮助和建议都会有很大帮助。
这是我最近一直在工作的代码
Public Class Form1
Dim StartTime As DateTime 'old current time
Dim PauseTime As DateTime 'keep track of the time when the timer is paused
Dim TotalTimePaused As TimeSpan 'The total amount of time paused
Private Sub BtnStart1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart1.Click
BtnStart1.Enabled = False
BtnPause1.Enabled = True
StartTime = DateTime.Now()
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'Subtract the current "Now" time from the start time
'and then subtract the total time paused
Dim ElapsedTime As TimeSpan = DateAndTime.Now.Subtract(StartTime).Subtract(TotalTimePaused)
Label2.Text = ElapsedTime.Hours.ToString.PadLeft(2, "0"c) + ":" + ElapsedTime.Minutes.ToString.PadLeft(2, "0"c) + ":" + ElapsedTime.Seconds.ToString.PadLeft(2, "0"c)
'And if you wanted the total elapsed time from time of start then
'subtract the current "Now" time from the start time only.
End Sub
Private Sub BtnPause1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPause1.Click
If Timer1.Enabled = False Then
BtnPause1.Text = "Pause"
'Add to the total time paused; the current time minus the
'time of pause. this will be the total amount of time
'paused so you can subtract it from the total amount of
'time since the start button was pressed
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Timer1.Enabled = True
Else
BtnPause1.Text = "Resume"
Timer1.Enabled = False
'Set the pause time so it can be
'calculated to the total time paused.
'when the timer is resumed
PauseTime = DateAndTime.Now
End If
End Sub
Private Sub BtnStop1_Click(sender As Object, e As EventArgs) Handles BtnStop1.Click
If Timer1.Enabled = False Then
BtnStart1.Enabled = True
BtnPause1.Text = "Pause"
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Else
Timer1.Enabled = True
End If
End Sub
End Class
【问题讨论】:
-
你不允许使用
Stopwatch类吗?