0

我正在尝试创建一个从指定时间开始倒计时的计时器。

用户输入时间并单击按钮。
单击按钮会打开第二个表单,其中包含一个计时器。
每次计时器计时,时间都会减少,剩余时间会显示在form2 ( ) 上的文本框中。textbox.text = timeLeft

但是,文本框永远不会真正更新。它保持空白,并且为属性分配新值真正起作用的唯一时间.text是如果我引发事件(例如单击将更改文本框.text属性的按钮)

*这是定时器类的代码

Public Class CountdownTimer

Private timeAtStart As Integer
Private timeLeft As Integer

Public Sub StartTimer(ByVal time As Integer)
    timeAtStart = time
    timeLeft = timeAtStart
    Timer1.Enabled = True
End Sub


Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick

    If timeLeft > 0 Then
        timeLeft = timeLeft - 1
        txtTimeLeft.Text = timeLeft.ToString

    Else
        Timer1.Stop()
        txtTimeRemaining.Text = "Time!"
        txtTimeRemaining.ForeColor = Color.Red
    End If

End Sub

End Class
  • 这就是我所说的:

    Dim timer As New CountdownTimer
    timer.Show()
    CountdownTimer.StartTimer(CInt(txtSetTime.Text))
    
4

5 回答 5

2

您的代码正在调用(表单)类而不是实例,我看不到 Timer1 在哪里被正确引用为独立的可重用类。这是实现可与其他形式一起使用的 CountDown 类的一种方法....

 Friend Class CountdownTimer

    Private timeAtStart As Integer
    Private timeLeft As Integer
    Private WithEvents Timer1 As New Timer
    Private txtTimeLeft as TextBox

   Public Sub New(TargetTB as TextBox)
       txtTimeLeft= TargetTB
   End Sub


   Public Sub StartTimer(ByVal time As Integer, timeLength as Integer) 
        timeAtStart = time
        timeLeft = timeLength 

        Timer1.Enabled = True
   End Sub


   Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)_
            Handles Timer1.Tick

       ' just dislaying time left
       If timeLeft > 0 Then
             timeLeft = timeLeft - 1
             txtTimeLeft.Text = timeLeft.ToString

       Else
           Timer1.Stop()
           txtTimeLeft.Text = "Time!"
           txtTimeLeft.ForeColor = Color.Red
      End If

   End Sub

End Class

如何使用它:

Dim CountDn As New CountdownTimer(frm.TextBoxToUse)

' use the INSTANCE name not the class name!!!!
'CountdownTimer.StartTimer(CInt(txtSetTime.Text))
CountDn.StartTimer(CInt(txtSetTime.Text))
于 2013-10-11T13:53:11.307 回答
0

This is your problem:

Dim timer As New CountdownTimer
timer.Show()
CountdownTimer.StartTimer(CInt(txtSetTime.Text))

You instantiate a new object called timer, but then start the timer on the CountdownTimer object

You need to change your code to this:

Dim timer As New CountdownTimer
timer.Show()
timer.StartTimer(CInt(txtSetTime.Text))
于 2013-10-11T14:33:42.510 回答
0

您确实意识到,当您倒计时时,您设置的文本框与完成时不同,对吧?

txtTimeLeft.Text 

VS

txtTimeRemaining.Text 

注意:计时器与 UI 在同一线程上运行,因此如果您的计算机(或程序)忙碌,计时器将不会以精确的时间间隔计时。如果您担心计时器的微小差异,您应该比较每个滴答事件期间计算机时间的差异,以确定已经过去了多少时间。

Dim TS = TimeSpan = Now.Subtract(StartingTime)
于 2013-10-11T14:01:49.650 回答
0

每次更新后尝试刷新文本框:

所以之后

txtTimeLeft.Text = timeLeft.ToString

添加

txtTimeLeft.Refresh
于 2013-10-11T14:24:57.223 回答
0

如果它在计时器完成后显示结果,我认为你应该使用

Application.DoEvents()

方法可以立即查看更新。它实际上适用于 Windows 窗体。你有什么尝试,所以我可以进一步帮助

于 2013-10-11T13:35:58.663 回答