VB中自定义事件和事件处理

一个包含事件的类:ClsWithEvents

ClsWithEvents类中,有两个属性Width和Height,这两个属性改变时会分别触发对应的Changed事件。

在 Public Event 声明了两个事件委托的原型

 

Public Class ClsWithEvents
    Private mWidth As Integer
    Private mHeight As Integer

    ' 事件委托的原型
    Public Event WidthChanged(ByVal newWdith As Integer)
    Public Event HeightChanged(ByVal newHeight As Integer)

    Public Property Width() As Integer
        Get
            Return mWidth
        End Get
        Set(ByVal value As Integer)

            If value <> mWidth Then
                RaiseEvent WidthChanged(value) ' 触发WidthChanged事件
            End If

            mWidth = value
        End Set
    End Property

    Public Property Height() As Integer
        Get
            Return mHeight
        End Get
        Set(ByVal value As Integer)

            If value <> mHeight Then
                RaiseEvent HeightChanged(value) ' 触发HeightChanged事件
            End If

            mHeight = value
        End Set
    End Property
End Class


 


 

事件的两种不同处理方法:

方法一、WithEvents关键字

 

Public Class Form1
    Private WithEvents objClsWithEvents As New ClsWithEvents


    Private Sub objClsWithEvents_HeightChanged(ByVal newHeight As Integer) _
        Handles objClsWithEvents.HeightChanged
        ' 处理 objClsWithEvents 的 HeightChanged 事件
    End Sub


    Private Sub objClsWithEvents_WidthChanged(ByVal newWdith As Integer) _
        Handles objClsWithEvents.WidthChanged
        ' 处理 objClsWithEvents 的 WidthChanged 事件
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles Button1.Click
        objClsWithEvents.Width = 200
        objClsWithEvents.Height = 200
    End Sub
End Class


 

方法二、AddHandler关键字

 

Public Class Form1
    Private Sub ClsWithEvents_HeightChanged(ByVal newHeight As Integer)
        ' 处理 ClsWithEvents 对象的 HeightChanged 事件
    End Sub

    Private Sub ClsWithEvents_WidthChanged(ByVal newWdith As Integer)
        ' 处理 ClsWithEvents 对象的 WidthChanged 事件
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim objClsWithEvents As New ClsWithEvents
        AddHandler objClsWithEvents.HeightChanged, AddressOf ClsWithEvents_HeightChanged
        AddHandler objClsWithEvents.WidthChanged, AddressOf ClsWithEvents_WidthChanged
        objClsWithEvents.Height = 200
        objClsWithEvents.Width = 200
    End Sub
End Class


 

你可能感兴趣的:(C#)