在函数内部处理事件

Handle event inside function

有没有办法在函数中获取事件处理程序?我需要处理一个 Tick 事件 (t.Tick)。这就是我的意思:

    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

如有任何帮助,我们将不胜感激。

Tick 事件句柄需要是一个单独的 Sub。创建计时器时,您可以提供将处理 Tick 事件的 Sub 地址。您需要在 class 级别变量中存储对 Label 的引用。

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