NITPRUDO NITPRUDO - 1 year ago 113 Question

Handle event inside function

Is there a way to get an event handler inside a function? I need to handle a Tick event (t.Tick). Here's what I mean:

Public Shared Function SetTime(ByVal x As Label)
Dim t As New Timer
t.Enabled = True
t.Interval = 100
'I need the handler here
x.Text = Date.Now.ToShortTimeString()
'I need the handler to end here
Return True
End Function

Any help would be appreciated.

Answer Source

The Tick event handle needs to be a separate Sub. When you create your timer, you can provide the address of the Sub that will handle the Tick event. You will need to store a reference to the Label in a class level variable.

Private Shared timeLabel As Label, myTimer As Timer

Public Shared Function SetTime(ByVal x As Label) As Boolean
    timeLabel = x

    myTimer = New Timer
    myTimer.Enabled = True
    myTimer.Interval = 100
    AddHandler myTimer.Tick, AddressOf myTimer_Tick
    Return True
End Function

Private Shared Sub myTimer_Tick(sender As Object, e As EventArgs)
    timeLabel.Text = Date.Now.ToShortTimeString()
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download