处理函数内部的事件

时间:2016-10-07 15:21:04

标签: vb.net function events handler

有没有办法在函数中获取事件处理程序?我需要处理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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

Tick事件句柄需要是一个单独的Sub。创建计时器时,您可以提供将处理Tick事件的Sub的地址。您需要在类级别变量中存储对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