如何在指定时间后停止计时器

时间:2017-01-08 10:48:32

标签: vb.net

我有3个texbox,它将持续运行随机数。 我可以知道如何在一定时间后停止计时器吗?

实施例 Timer1在5秒后停止 Timer2在10秒后停止 TImer2在15秒后停止

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Dim num1 As Integer
            Dim rnd As New Random()

            num1 = rnd.[Next](0, 2)
            TextBox1.Text = Convert.ToString(num1)

        End Sub
    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
            Dim num1 As Integer
            Dim rnd As New Random
            num1 = rnd.[Next](1, 9)
            TextBox2.Text = Convert.ToString(num1)
        End Sub

        Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
            Dim num1 As Integer
            Dim rnd As New Random
            num1 = rnd.[Next](1, 9)
            TextBox3.Text = Convert.ToString(num1)
        End Sub
  Private Sub btnrndpick_Click(sender As Object, e As EventArgs) Handles btnrndpick.Click
        Timer1.Enabled = True
        Timer2.Enabled = True
        Timer3.Enabled = True
        Timer4.Enabled = True
        Timer5.Enabled = True
        btnrndpick.Text = "RUNNING"
    End Sub

2 个答案:

答案 0 :(得分:0)

这是一种只使用1个计时器的方法:

Private Rnd As New Random()
Private buttonPressTime As DateTime

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 2) Then
        SetTextBoxText(TextBox1, 0, 2)
    End If
    If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 5) Then
        SetTextBoxText(TextBox2, 1, 9)
    End If
    If (DateTime.Now - buttonPressTime) < New TimeSpan(0, 0, 15) Then
        SetTextBoxText(TextBox3, 1, 9)
    Else
        Timer1.Stop()
    End If
End Sub

Private Sub SetTextBoxText(ByVal TextBox As TextBox, ByVal LowerBound As Integer, ByVal UpperBound As Integer)
    TextBox.Text = Rnd.[Next](LowerBound, UpperBound).ToString()
End Sub

Private Sub btnrndpick_Click(sender As Object, e As EventArgs) Handles btnrndpick.Click
    Timer1.Enabled = True
    buttonPressTime = DateTime.Now
    btnrndpick.Text = "RUNNING"
End Sub

答案 1 :(得分:0)

您是否尝试过使用整型变量? 像

这样的东西

Dim number as integer = 0

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick number += 1 If number = 5 Then 'For example. But you need to adjust the tick property. Timer1.Stop End Sub