如何在VB.NET中编写事件处理程序?

时间:2012-09-03 05:49:35

标签: .net vb.net events event-handling visual-studio-2005

我试图在VB.NET中测试非常简单的事件处理。

到目前为止,我有:

Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate

Sub MySub
    Raise TestEvent
End Sub

如何为刚刚显示简单MessageBox的上述事件编写事件处理程序?

2 个答案:

答案 0 :(得分:4)

编写处理程序方法很简单 - 只需编写一个不带参数的Sub并显示一个消息框。

然后,您需要为该事件订阅处理程序,您可以在该方法中添加Handles子句:

Sub ShowMessageBox() Handles foo.TestEvent

或者使用AddHandler声明:

AddHandler foo.TestEvent, AddressOf ShowMessageBox

请注意,要遵循.NET约定,您的委托应该有两个参数 - 一个类型为Object以指定引发事件的对象,另一个类型为EventArgs或子类,以提供任何参数额外的信息。这不是语言的必需,但它是一个广泛遵循的惯例。

答案 1 :(得分:3)

在VB中,我们有两种方法来订阅Publisher类的事件。

'Delegate
Public Delegate Sub TestEventDelegate()

'Event publisher class that publishes and raises an event

Public Class EventPublisher
    Private _num As Integer
    Public Event NumberChanged As TestEventDelegate
    Public Property Number As Integer
        Get
            Return _num
        End Get
        Set(value As Integer)
            _num = value
            RaiseEvent NumberChanged()
        End Set
    End Property
End Class

'Event subscriber class

Public Class EventSubscriber
    'instance of EventPublisher class
    Private WithEvents myObject As New EventPublisher

    'Handler of myObject.NumberChanged event
    Public Sub ShowMessage() Handles myObject.NumberChanged
        Console.WriteLine("Value has been changed")
    End Sub

    Shared Sub Main()
        Dim es As New EventSubscriber
        es.myObject.Number = 10
        es.myObject.Number = 20

        'Handle the events dynamically using AddHandler
        Dim ep1 As New EventPublisher
        ep1.Number = 101
        'Attach an event to the handler
        AddHandler ep1.NumberChanged, AddressOf TestIt
        ep1.Number = 102
    End Sub
    Shared Sub TestIt()
        Console.WriteLine("Number is modified")
    End Sub
End Class