Ever wanted to have a better Timer as a class, but have been bothered by the fact that you still need to have two files?
SetTimer API requires that you give an address of a callback procedure that the timer then triggers. Working around the issue has been a problem because AddressOf only works for procedures in a regular module.
This shouldn't worry you anymore. This is a single file solution that has it's roots on the famous SelfSub/SelfHook/SelfCallback solution by Paul Caton and LaVolpe. In this class however the code has been modified and simplified to fit the use of a simple timer.
Events
Timer(Seconds)
This event triggers just like the regular Timer event. Unlike the regular Timer control, you also get the value that tells how many seconds has passed since the first call. The seconds value is reseted always when Interval property is changed, but you may change the Enabled property without reseting the starting time.
Properties
Enabled
Returns or sets whether the timer is enabled or not. By default this is True. However the timer does not run if Interval is 0 even if it is enabled. Enabled is automatically swithed to False if for some reason the initialization of the timer fails. The timer is initialized every time Enabled = True and Interval > 0.
Interval
Returns or sets the interval of the timer in milliseconds. Can only be 0 or a positive value. By default the value is 0.
Usage
In the general declarations, add the following:
Dim WithEvents Timer As SelfTimer
This way you add the control with the Timer event to the form or object. When you wish to initialize the timer:
Set Timer = New SelfTimer
Timer.Interval = 1000
This creates the timer and makes it trigger Timer event every one second. Also remember to cleanup once you're done:
Set Timer = Nothing
Because of using WithEvents, you also have a procedure where you can place the code you want to run.
Code:
Private Sub Timer_Timer(ByVal Seconds As Currency)
' your code here
End Sub
A demonstration is included in the attachment. Enjoy!