我想知道如何设置倒数计时器,以便以小时:分钟:秒来显示时间?
当前,它仅输出秒,我不确定哪里出错了。
任何帮助深表感谢。
代码:
Public Class Form1
Dim TargetDT As DateTime
Dim fields() As String
Dim Days, Hours, minutes, seconds, milliseconds As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
fields = Split(TextBox1.Text, ":")
Hours = fields(0)
minutes = fields(1)
seconds = fields(2)
Dim CountDownFrom As TimeSpan = TimeSpan.FromHours(Hours).FromMinutes(minutes).FromSeconds(seconds)
Timer1.Interval = 1000
TargetDT = DateTime.Now.Add(CountDownFrom)
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
Con1Time.Text = ts.ToString("hh\:mm\:ss")
Else
Con1Time.Text = "0:00:00"
Timer1.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
答案 0 :(得分:0)
首先将要倒数的时间分配给TimeSpan
字段。当您想开始倒数计时时,请分别在Start
和Timer
上呼叫Stopwatch
。在Tick
的{{1}}事件处理程序中,获取Timer
的{{1}}并将其从原始时间中减去以得到剩余时间Elapsed
。然后,您可以格式化并显示它。当剩余时间为零时,倒计时结束。
Stopwatch
也就是说,您的具体问题在这里:
TimeSpan
那并没有您所想的那样。您只会得到Private countDownTime As TimeSpan
Private countDownWatch As Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
countDownTime = TimeSpan.FromMinutes(30)
countDownWatch = Stopwatch.StartNew()
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timeRemaining = countDownTime - countDownWatch.Elapsed
If timeRemaining < TimeSpan.Zero Then
timeRemaining = TimeSpan.Zero
End If
Label1.Text = timeRemaining.ToString("hh\:mm\:ss")
If timeRemaining = TimeSpan.Zero Then
Timer1.Stop()
MessageBox.Show("Countdown complete")
End If
End Sub
调用的结果。如果您想用小时,分钟和秒创建一个Dim CountDownFrom As TimeSpan = TimeSpan.FromHours(Hours).FromMinutes(minutes).FromSeconds(seconds)
,请调用适当的构造函数
FromSeconds
当然,这些参数应该是TimeSpan
的值,而不是Dim CountDownFrom As TimeSpan = New TimeSpan(Hours, minutes, seconds)
。转到Integer
并使用适当的数据类型。