如何在 visual basic 中控制计时器,其中计时器的时间间隔由用户从文本框设置

How to control a timer in visual basic where the time interval of the timer is set by the user from a textbox

我是 visual basic 的新手,我正在尝试 运行 用户设置的时间间隔内的一系列代码,后者可以随时从文本框中更改。请在附件中找到我创建的界面。

我建议您在每次用户通过处理TextBox.TextChanged 事件(您可以添加或不添加适当的错误处理)。

一个例子:

Friend WithEvents Timer1 As New System.Windows.Forms.Timer

Private Sub ResetTimerInterval(ByVal tmr As Timer, ByVal interval As Integer)
    If (tmr IsNot Nothing) Then
        With tmr
            .Stop()
            .Enabled = False
            .Interval = interval 
            .Enabled = True
            .Start()
        End With
    End If
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged

    Dim value As Integer

    If Integer.TryParse(DirectCast(sender, TextBox).Text, value) Then
        Me.ResetTimerInterval(value)
    End If

End Sub

如果你也想知道当前的Interval,你可以通过添加一个属性:

来跟踪它
Friend WithEvents Timer1 As New System.Windows.Forms.Timer

Private Property TimerInverval As Integer
    Get
        Return Me.timerIntervalB
    End Get
    Set(ByVal value As Integer)
        If (value <> Me.timerIntervalB) Then
            Me.timerIntervalB  = value
            Me.ResetTimerInterval(value)
        End If
    End Set
End Property
' Backing field.
Private timerIntervalB As Integer

Private Sub ResetTimerInterval(ByVal tmr As Timer, ByVal interval As Integer)
    If (tmr IsNot Nothing) Then
        With tmr
            .Stop()
            .Enabled = False
            .Interval = interval 
            .Enabled = True
            .Start()
        End With
    End If
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged

    Dim value As Integer

    If Integer.TryParse(DirectCast(sender, TextBox).Text, value) Then
        Me.timerIntervalB = value
    End If

End Sub