首先强制自定义事件处理程序

时间:2017-07-14 20:54:21

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

当我创建自定义处理程序时:

Public Class MyCustomClass
    Public Sub AddHandlers()
        AddHandler Form1.MouseMove, AddressOf MoveMouse
    End Sub
    Private Sub MoveMouse(sender As Object, e As MouseEventArgs)
        MsgBox("Needs to happen first.")
    End Sub
End Class

当用户将鼠标移到Form1上时,我需要在此类中使用MoveMouse在任何其他事件之前触发。

Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
    MsgBox("Needs to happen second.")
End Sub

在写这篇文章时,我意识到我可以在Form1的类中创建另一个自定义事件处理程序,但还有其他方法可以确保MoveMouse(不管它在哪个类中)在Form1_MouseMove之前发生吗?

Thanks- 〜尼克

1 个答案:

答案 0 :(得分:0)

事件按声明的顺序触发:

因此,如果您希望自定义类在Form1引发事件之前在Form1上引发MouseMove,则需要先使自定义类添加处理程序:

Public Class CustomClass
    Public Sub OnMouseMoved(sender As Object, e As MouseEventArgs)
        Console.WriteLine("Custom mouse moved")
    End Sub
End Class

Public Class Form1
    Public Custom As CustomClass
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Custom = New CustomClass
        AddHandler MouseMove, AddressOf Custom.OnMouseMoved
        AddHandler MouseMove, AddressOf OnMouseMoved
 End Sub

    Private Sub OnMouseMoved(sender As Object, e As MouseEventArgs)
        Console.WriteLine("Form1 mouse moved")
    End Sub
End Class