如何在VB.Net中删除计时器延迟

时间:2014-02-13 22:00:03

标签: vb.net winforms

我正在使用VB.Net制作一个简单的倒数计时器,但是当它与实际的倒数计时器进行比较时,VB.Net会丢失几秒钟。我该怎么做才能防止这种情况发生?

'Variables used to countdown time
Dim HoursRemaining As Integer = 0
Dim MinsRemaining As Integer = 0
Dim SecondsRemaining As Integer = 0
'These are needed to get the time remaining into the format 00:00:00
Dim HoursStr As String
Dim MinsStr As String
Dim SecsStr As String

Private Sub TimeRemainingTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimeRemainingTimer.Tick
    If HoursRemaining = 0 And MinsRemaining = 0 And SecondsRemaining = 0 Then
        TimeRemaining.Text = "00:00:00"
        TimeRemainingTimer.Stop()
    End If

    If MinsRemaining = 0 And HoursRemaining > 0 Then
        MinsRemaining = 60
        HoursRemaining = HoursRemaining - 1
    End If
    If SecondsRemaining = 0 Then
        SecondsRemaining = 60
        MinsRemaining = MinsRemaining - 1
    End If

    SecondsRemaining = SecondsRemaining - 1
    TimeRemainingUpdate(SecondsRemaining)
End Sub

Private Sub TimeRemainingUpdate(ByVal SecondsRemaining As Integer)
    Do While eLength >= 60
        HoursRemaining = HoursRemaining + 1
        eLength = eLength - 60
    Loop

    If HoursRemaining Like "[0-9]" Then
        HoursStr = "0" & HoursRemaining
    Else
        HoursStr = HoursRemaining
    End If
    If MinsRemaining Like "[0-9]" Then
        MinsStr = "0" & MinsRemaining
    Else
        MinsStr = MinsRemaining
    End If
    If SecondsRemaining Like "[0-9]" Then
        SecsStr = "0" & SecondsRemaining
    Else
        SecsStr = SecondsRemaining
    End If

    TimeRemaining.Text = HoursStr & ":" & MinsStr & ":" & SecsStr
End Sub

2 个答案:

答案 0 :(得分:2)

将当前系统时间存储在开始状态,然后使用当前系统时间和开始系统时间之间的差异来计算屏幕上显示的内容。

答案 1 :(得分:0)

这不是您问题的答案,但它会简化您的代码。也许这会帮助你发现错误:

' Initialization
Dim counter as New TimeSpan(TimeSpan.FromSeconds(120)) ' set your initial seconds here

Private Sub TimeRemainingTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimeRemainingTimer.Tick
    counter.AddSeconds(-1)
    TimeRemainingUpdate()
End Sub

Private Sub TimeRemainingUpdate()
    TimeRemaining.Text = counter.ToString("hh:mm:ss")  
End Sub

在勾选内部,您必须检查TimeSpan是否实际达到零