Search code examples
vb.netwinformstimer

Using timers in vb


I do not understand how to utilize the timers in vb.net I want to make a simple program where when I press a button the timer starts and the label changes it's number every second until 60 seconds have passed. I think I should put this in the button event

Timer1.Start()

But I am unsure of what to do from there. How do I go about doing this?


Solution

  • Well Timer1.Start() starts the timer, but you need to declare how often the timer ticks.

    Timer1.Interval = 1000
    

    will make the timer tick every 1000 miliseconds, or 1 sec. The actions that you want to happen for the timer go in the Timer_Tick event handler.

    In order to allow the label to increment you could use a global variable:

    Public Class MainBox
    
    Dim counter As Int
    
    Private Sub Form_Load(sender As System.Object, e As System.EventArgs)
        Timer1.Interval = 1000
        Timer1.Start()
    End Sub
    
    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) HandlesTimer1.Tick<action>
        counter = counter + 1
        label1.Text = counter
    End Sub