vb.net 在 vb 中使用定时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25191727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using timers in vb
提问by Todd432
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
我不明白如何在 vb.net 中使用计时器我想制作一个简单的程序,当我按下按钮时,计时器启动并且标签每秒更改一次数字,直到 60 秒过去。我想我应该把它放在按钮事件中
Timer1.Start()
But I am unsure of what to do from there. How do I go about doing this?
但我不确定从那里开始做什么。我该怎么做?
回答by Chase Ernst
Well Timer1.Start()starts the timer, but you need to declare how often the timer ticks.
好Timer1.Start()启动计时器,但您需要声明计时器滴答的频率。
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_Tickevent handler.
将使计时器每 1000 毫秒或 1 秒滴答一次。您希望为计时器执行的操作进入Timer_Tick事件处理程序。
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
回答by Nizam
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 INTERVALproperty):
您需要定义 Tick 事件处理程序,该处理程序将在时间滴答时执行操作(它将在每个时间间隔内打勾 - 以毫秒为单位 - 在INTERVAL属性中定义):
Start the timer:
启动定时器:
Timer1.Start()
Define INTERVAL property (2 seconds in the following example):
定义 INTERVAL 属性(以下示例中为 2 秒):
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()
如果你愿意,你可以使用 Timer1.Stop()
回答by Neolisk
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:
不要忘记启用计时器并设置间隔(1000 应该足够了,但您可以保留默认的 100)。在 Tick 处理程序中放置用于刷新标签的代码。启动计时器时,请记住开始时间 ( Date.Now)。然后,在每个滴答声中:
lbl.Text = Date.Now.Subtract(startDate).TotalSeconds.ToString("N0")

