need assistance with timers in VB.Net

Leros

Lifer
Jul 11, 2004
21,867
7
81
I've been playing around with a little VB.Net just for fun. I'm trying to get a function to run every x seconds (say a clock that updates the time every second). I keep finding code on the internet similiar to this:

Dim t As New System.Timers.Timer(2000)

AddHandler t.Elapsed, AddressOf TimerFired <---- what does this line do?

Public Sub TimerFired(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
'Do stuff Here
End Sub

Source

Basically I have been putting the code I want to execute inside of the TimerFired() method. Everything compiles fine, but nothing happens when I run the program. I can't seem to find any useful information on the internet. That or I'm missing something really basic here.

Also, does anyone know of any nice resources on the internet for VB.Net?
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
Is this code in a windows form? It must be or it will exit the moment it is called.

Also did you start the timer?

t.Enabled = True
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
No, the code is not in a windows form, it is in a class library. I have enabled the timer.
 

brentman

Senior member
Dec 4, 2002
628
0
0
AddHandler t.Elapsed, AddressOf TimerFired

These statements are used to assign handlers to dynamically created controls. By default your new dynamic control (timer t) will not have any event handler. It works for any other control as well.

i.e.

dim myBtn as new button
AddHandler myBtn.click, addressof ButtonClick

sub ButtonClick(s as object, e as eventargs)
'code here
end sub

You may want to specify other properties to your dynamic timer to ensure it has the values that you want. Do this after you declare it.
dim t as new timer
t.delay = 'value you wish in milliseconds.
t.enabled = true


I hope that helps explain what the addhandler does. Sorry if I made things worse.

- brent
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
Originally posted by: brentman
AddHandler t.Elapsed, AddressOf TimerFired

These statements are used to assign handlers to dynamically created controls. By default your new dynamic control (timer t) will not have any event handler. It works for any other control as well.

i.e.

dim myBtn as new button
AddHandler myBtn.click, addressof ButtonClick

sub ButtonClick(s as object, e as eventargs)
'code here
end sub

You may want to specify other properties to your dynamic timer to ensure it has the values that you want. Do this after you declare it.
dim t as new timer
t.delay = 'value you wish in milliseconds.
t.enabled = true


I hope that helps explain what the addhandler does. Sorry if I made things worse.

- brent

Ah, the AddHanlder thing makes sense now.