如何在VB.net中创建一个显示分钟的倒数计时器?

时间:2019-05-18 07:20:24

标签: vb.net

我正在尝试制作一个显示分钟的倒数计时器。不幸的是,当我尝试运行它时,分钟数比预期的要快得多。计时器间隔为1000(1秒)。如何解决此问题并使其成为可运行的计时器?我尝试了许多不同的方法来使此倒数,所以关于替代方法的任何建议也都不错。此刻我在几分钟和几秒钟内使用了不同的标签。

Public Class Form1
    Dim CurrentTime As Integer

    Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
        End
    End Sub
    Private Sub Form1_MouseMove()

    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        tmrStart.Enabled = True
        CurrentTime = 180


    End Sub

    Private Sub tmrStart_Tick(sender As Object, e As EventArgs) Handles tmrStart.Tick
        CurrentTime = CurrentTime - 1
        lblSeconds.Text = (CurrentTime / 3) * 10
        If CurrentTime < 180 And CurrentTime > 120 Then
            lblMinutes.Text = "2"
        ElseIf CurrentTime < 120 And CurrentTime > 60 Then
            lblMinutes.Text = "1"
        ElseIf CurrentTime < 60 And CurrentTime > 0 Then
            lblMinutes.Text = ""
        End If
    End Sub

    Private Sub lblSeconds_Click(sender As Object, e As EventArgs) Handles lblSeconds.Click

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CurrentTime = 180
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

如果您要处理时间,那么最好使用Date类型。如果您将currentTime声明为日期,可以使代码更简洁-

Dim CurrentTime As Date

然后,在其中分配要使用的值

CurrentTime =#0:3:0#

-3分钟..

然后将以下子项更改为这些

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    tmrStart.Enabled = True
    CurrentTime = #0:3:0#
End Sub

Private Sub tmrStart_Tick(sender As Object, e As EventArgs) Handles tmrStart.Tick
    CurrentTime = CurrentTime.AddSeconds(-1)
    lblSeconds.Text = CurrentTime.Second.ToString
    lblMinutes.Text = CurrentTime.Minute.ToString
    If CurrentTime = #0:0:0# Then
        tmrStart.Enabled = False
    End If
End Sub

更干净,更容易看到发生了什么。同样,用于确定原始代码中显示的分钟的语句似乎可以正常工作,但是当剩余秒数恰好是120或60秒时,标签实际上并不会得到更新。在您的代码中不要紧,但是要在逻辑上正确,它们应该是

    If CurrentTime < 180 And CurrentTime >= 120 Then
        lblMinutes.Text = "2"
    ElseIf CurrentTime < 120 And CurrentTime >= 60 Then
        lblMinutes.Text = "1"
    ElseIf CurrentTime < 60 And CurrentTime >= 0 Then
        lblMinutes.Text = ""
    End If

最后的小事情,您的代码中没有任何东西可以禁用计时器,因此剩余时间变为0

不要被这些事情拖延-人类是容易犯错误的-我和其他人一样多。