如何从正在运行的倒数计时器中减去时间?

时间:2016-12-01 01:50:21

标签: vb.net timer

基本上,我有一个计时器,在用户参加测试时从3分钟倒计时。如果用户跳过一个问题,我想要承担15秒的罚款。因此,他们的完成时间缩短了15秒。示例:计时器位于2:35。用户点击跳过,计时器下降到2:20,然后继续。这是我的代码:

Public Class Form1
    Private TargetDT As DateTime
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.AcceptButton = btnprocess
    End Sub
    Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
        Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
        If ts.TotalMilliseconds > 0 Then
            lbltimer.Text = ts.ToString("mm\:ss")
        Else
            lbltimer.Text = "00:00"
            tmrCountdown.Stop()
            MessageBox.Show("Done")
        End If
    End Sub

    Private Sub btnskip_Click(sender As Object, e As EventArgs) Handles btnskip.Click
        ' This is where I want to subtract 15 seconds
        Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now.Add(TimeSpan.FromSeconds(15)))
    End Sub

    Private Sub btnbegin_Click(sender As Object, e As EventArgs) Handles btnbegin.Click
        tmrCountdown.Interval = 1
        TargetDT = DateTime.Now.Add(TimeSpan.FromMinutes(2.5))
        tmrCountdown.Start()
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

只需更改TargetDT值,以便在下一个Tick事件中更新显示。

我还将您的代码更改为使用DateTime.UtcNow而不是DateTime.Now,因此聪明的用户无法更改时区以获得额外的时间(因为更改时区不需要管理/提升权限)

您也不需要指定超高定时器频率(您将其设置为每毫秒更新一次)。这太过分了。我将它设置为4Hz,因此屏幕显示不会太滞后。

Private Sub btnskip_Click(sender As Object, e As EventArgs) Handles btnskip.Click

    Me.TargetDT = Me.TargetDT.Subtract( TimeSpan.FromSeconds( 15 ) )

End Sub

Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick

    Dim now As DateTime = DateTime.UtcNow

    If now > Me.TargetDT Then

        Me.lbltimer.Text = "00:00"
        Me.tmrCountdown.Stop()
        MessageBox.Show("Done")

    Else

        Dim diff As TimeSpan = Me.TargetDT - now
        Me.lbltimer.Text = diff.ToString("mm\:ss")

    End If

End Sub

Private Sub btnbegin_Click(sender As Object, e As EventArgs) Handles btnbegin.Click

    Me.tmrCountdown.Interval = 250 ' no need to update more than 4 times a second
    Me.TargetDT = DateTime.UtcNow.Add( TimeSpan.FromMinutes(2.5) )

    Me.tmrCountdown.Start()
End Sub