我正在尝试将倒数计时器放入我的程序中,但是当我运行该程序时,它不会倒计时。它会跳到一个,就是这样。
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 routuine中将间隔声明为500。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
依靠时间间隔标记时间的推移会导致不准确。