Is it possible to pass a reference to a timer from a form (where the timer must be) to instantiated objects of a class? The idea is that when the timer event fires, each object will also receive the event and act upon it autonomously.
It certainly is. Here is a simple example. Create a new project. Add a form (Form1) with two command buttons and a timer. Drop in the following code: [tt]
Option Explicit
Public myClass1 As Class1
Public myclass2 As Class1
Private Sub Command1_Click()
Set myClass1 = New Class1
Set myclass2 = New Class1
myClass1.RefTimer = Form1.Timer1
myClass1.ClassMessage = "First object"
myclass2.RefTimer = Form1.Timer1
myclass2.ClassMessage = "Second object"
End Sub
Private Sub Command2_Click()
Timer1.Interval = 1000
Timer1.Enabled = True
End Sub [/tt]
Now add a class module (Class1) to your project, and drop in the following code: [tt]
Option Explicit
Private WithEvents clsTimer As Timer
Private mvarMessage As String
Private Sub clsTimer_Timer()
Debug.Print mvarMessage
End Sub
Public Property Let RefTimer(objTimer As Timer)
Set clsTimer = objTimer
End Property
Public Property Let ClassMessage(strMessage As String)
mvarMessage = strMessage
End Property [/tt]
When you run the program, clicking Command1 will create two instances of Class1, both with references to our source timer on the form. Clicking Command2 enables our form timer only - but causes the timer event in each of our class instances to fire.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.