I'm trying to create a generic event handler

JA12

Member
Joined
Jul 2, 2013
Messages
17
Location
Ireland
Programming Experience
10+
I've got a form with multiple controls, including buttons.

The form is dynamically generated so all the active controls have generated unique names.

I'm trying to generate a generic MouseClick handler that captures all button clicks, no matter what button is clicked. My major problem is that the "Handles Me.MouseClick" never activates, the only Event that seems to capture any Event at all is "Handles Me.MouseEnter" which only has "System.EventArgs" rather than the more useful "System.Windows.Forms.MouseEventArgs". The "sender" for the MouseEnter Event is not the button that was clicked, it's the form itself, so it's useless.

VB.NET:
Private Sub CheckEvent(sender As System.Object,
                           e As System.EventArgs) Handles Me.MouseEnter
        Dim btn As String()
        Dim sName As String
        Dim sType As String = sender.GetType.ToString

        Select Case sender.GetType.ToString
            Case "System.Windows.Forms.Button"
                btn = Split(sender.name, "_", -1, CompareMethod.Text)
                sName = btn(0)
                ProcessClick(sender)
                Stop
            Case "System.Windows.Forms.TableLayoutPanel"
                Stop
            Case Else
                ' ignore everything else
                Stop                                          '<---- always ends up here
        End Select
    End Sub
These never activate
VB.NET:
Private Sub <form>_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
Private Sub <form>_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
Private Sub <form>_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
This always activates
VB.NET:
Private Sub <form>_MouseEnter(sender As Object, e As System.EventArgs) Handles Me.MouseEnter
       Stop
End Sub
All the examples online deal with a common handler for KNOWN controls, not for unknown controls.

Any ideas anyone?
 
If you want to handle events of arbitrary objects then don't use Handles clauses. Write the event handler without the Handles clause and then use the AddHandler statement to attach it to the events you want to handle, e.g.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each btn In Me.Controls.OfType(Of Button)()
        AddHandler btn.MouseClick, AddressOf Button_MouseClick
    Next
End Sub

Private Sub Button_MouseClick(sender As Object, e As MouseEventArgs)
    '...
End Sub
 
Back
Top