Blatz Blatz - 26 days ago 7
Vb.net Question

How can I make Timer do different things based on how it was started

How can I make my Timer do different things depends on what activated it? I've tried using this code

Dim a As Integer = 0
Dim b As Integer = 0

Private Sub Button1_MouseHover(sender As Object, e As EventArgs) Handles Button1.MouseHover
Timer1.Start
End Sub

Private Sub Button2_MouseHover(sender As Object, e As EventArgs) Handles Button2.MouseHover
Timer1.Start
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick, Button2.MouseHover, Button1.MouseHover
If sender Is Button1 Then
a = a + 1
TextBox1.Text = a
End If

If sender Is Button2 Then
b = b + 1
TextBox2.Text = b
End If
End Sub


but Textbox just add 1 once. This means that the Timer just act one time not continuously like Timer usually do. So is there anything I do wrong there, or i can do something different?.

Answer

Another possibly simpler approach, would be to use the Timer.Tag property and use one handler for both buttons:

Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
    Timer1.Tag = sender
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    a += 1
    If Timer1.Tag Is Button2 Then
        TextBox1.Text = a.ToString
    End If
    If Timer1.Tag Is Button1 Then
        TextBox2.Text = a.ToString
    End If
End Sub

Since Tag is already of type Object no external casting is needed.

I included the Start function, since I wasn't sure how you're initially starting the timer. If you're doing in a different manner it can be left out of the button event handler

Comments