3

我试图在我的程序中放置一个倒数计时器 insde 我的标签,但是当我运行程序时它不会倒计时。它直接跳到一个,就是这样。

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Dim Time As Integer = 11
    Do Until Time = 0
        ClockLabel.Text = "Compacting database in: " & Time
        Time -= 1
    Loop
End Sub

我还启动了计时器并在 Form_Load 例程中将间隔声明为 500。

4

4 回答 4

5

摆脱循环并在范围之外声明 Time 变量。

Dim Time As Integer = 11

Private Sub CompactTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
                              Handles CompactTimer.Tick
  If Time >= 0 Then
    ClockLabel.Text = "Compacting database in: " & Time
    Time -= 1
  Else
    CompactTimer.Stop
  End If
End Sub
于 2013-07-02T16:16:21.460 回答
3

做一个静态变量..

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Static Time As Integer = 11

    ClockLabel.Text = "Compacting database in: " & Time
    Time -= 1
    If Time = 0 Then CompactTimer.Stop

End Sub
于 2013-07-02T16:17:57.950 回答
2

每次计时器滴答时都会发生循环。你很可能想要这样的东西:

Dim time as Integer = 11 ' Declare outside
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick
    If Time = 0 Then
        CompactTimer.Enabled = False ' Disable timer
        ClockLabel.Text = "Compacting database now"
    Else
        ClockLabel.Text = "Compacting database in: " & time
        time -= 1
    End If
End Sub
于 2013-07-02T16:17:51.133 回答
2

如果您希望代码显示实际时间量,则代码可能如下所示。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'start the count down
    CompactTimer.Interval = 500
    CompactTimer.Start()
    stpw.Stop()
    stpw.Reset()
    stpw.Restart()
End Sub

Dim stpw As New Stopwatch
Dim countdown As New TimeSpan(0, 0, 11) 'length of countdown in seconds

Private Sub CompactTimer_Tick(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) Handles CompactTimer.Tick
    Dim togo As TimeSpan = countdown - stpw.Elapsed
    If togo.TotalSeconds > 0 Then
        ClockLabel.Text = String.Format("Compacting database in: {0} secs.", togo.TotalSeconds.ToString("n0"))
    Else
        CompactTimer.Stop()
    End If
End Sub

依靠间隔来标记时间的流逝会导致不准确。

于 2013-07-02T16:57:28.697 回答