您的位置:首页 > 编程语言 > VB

vb.net timer 定时器

2016-02-24 11:14 483 查看
.net使用timer做计数器是,不要使用循环调用的方式,否则计数器会以2的N次方累加,最终文本框的显示结果是,1,2,4,8,16,而不是1,2,3,4,5...,代码如下:

'需要用到的控件,一个textbox,一个timer

Sub myCounter ()

try

TextBox1.Text = (Int(TextBox1.Text) +
1).ToString ‘文本框数字加1

Timer1.Interval = 1 1000

If Timer1.Enabled = False Then

Timer1.Start()

End If

AddHandler Timer1.Tick, AddressOf myCounter

Catch ex As Exception

MsgBox("程序错误:" +
ex.ToString)

End Try

为了避免上述问题(上述问题,可能是每次运行都开启一个timer线程)请直接在timer控件的促发时间里加入代码,即可避免,如下

Private Sub Timer1_Tick(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Timer1.Tick

Call myCounter()

End Sub

Sub myCounter ()

try

TextBox1.Text = (Int(TextBox1.Text) + 1).ToString ‘文本框数字加1

Timer1.Interval = 1000

If Timer1.Enabled = False Then

Timer1.Start()

End If

AddHandler Timer1.Tick, AddressOf mycounter

Catch ex As Exception

MsgBox("程序错误:" + ex.ToString)

End Try
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: