NITPRUDO NITPRUDO - 1 month ago 16
Vb.net 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
t.Start()
'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

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
    myTimer.Start()
    Return True
End Function

Private Shared Sub myTimer_Tick(sender As Object, e As EventArgs)
    timeLabel.Text = Date.Now.ToShortTimeString()
End Sub
Comments