Search code examples
vb.netwinformstimerlogicuser-input

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


I am new to visual basic and I am trying to run a series of codes at a time interval set by the user which the latter can change any time from the text box. please find attached the interface I've created.

user input form


Solution

  • I will suggest you to set the interval value every time that the user puts a right Integer value inside the TextBox by handling the TextBox.TextChanged event (you can add or not a proper error-handling).

    An example:

    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
    

    If you also want to know the current Interval, you can track it by adding a Property:

    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