Using timers in vb

2019-09-19 12:12发布

问题:

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?

回答1:

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


回答2:

You need to define the Tick event handler that will do the actions when time ticks (it will tick every interval - in miliseconds - defined in INTERVAL property):

Start the timer:

Timer1.Start()

Define INTERVAL property (2 seconds in the following example):

Timer1.Interval = 2000 

Define the event handler

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    <action>
    IF <condition> THEN Timer1.Stop()
End Sub

If you want you can stop the timer using Timer1.Stop()



回答3:

Don't forget to enable the Timer and set interval (1000 should be good enough, but you can leave the default 100). Inside a Tick handler put code to refresh the label. As you start the timer, remember the start time (Date.Now). Then, at every tick:

lbl.Text = Date.Now.Subtract(startDate).TotalSeconds.ToString("N0")