Search code examples
vb.netvisual-studioeventsevent-handlingaddhandler

Force Custom Event Handler First


When I create custom handlers like:

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

I need MoveMouse in this class to fire before any other event when the user moves their mouse over Form1.

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

While writing this, I realized I could create yet another custom event handler in Form1's class, but is there any other way to ensure that MoveMouse (regardless of what class it is in) happens before Form1_MouseMove?

Thanks- ~Nic


Solution

  • Events are fired in the order in which they are declared:

    So if you want your custom class to raise MouseMove on Form1 before Form1 raises the event you need to make your custom class add the handler first:

    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