Using timers in vb

寵の児 提交于 2019-12-25 18:33:16

问题


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")


来源:https://stackoverflow.com/questions/25191727/using-timers-in-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!