I\'ve written some code to handle an event as follows:
AddHandler myObject.myEvent, AddressOf myFunction
It seemed that everything was work
You may use IsHandleCreated
property to check your event already has an handle or not.
If e.Control.IsHandleCreated = False Then
AddHandler e.Control.KeyPress, AddressOf TextBox_keyPress
End If
I know I am a few years late to the game but you could always scope a class variable and then set it after the fact. This is not a totally hardened way of doing things but it is better than just hoping you did not have something or re adding it every time. In my case I used this in a WinForms app were I wanted to add a handler for dragging and dropping onto a datagridview surface. I wanted to stop this functionality if part of another datagridview was not yet filled out completely that it was dependent on.
So it would be like this:
Class level
Private _handlersAdded As Boolean = False
Constructor:
Public Sub New()
AddHandler dgv.DragEnter, AddressOf DragEnter
_handlersAdded = True
End Sub
Method that determines issue:
Private Sub CheckRowsAreDone()
For Each row As DataGridViewRow In dgv.Rows
Dim num = 0
For i = 0 To row.Cells.Count - 1
Dim val = If(Not String.IsNullOrEmpty(row?.Cells(i)?.Value?.ToString), 1, -1)
num += val
Next
If num > -(row.Cells.Count) And num < (row.Cells.Count) Then
RemoveHandler dgv.DragEnter, AddressOf DragEnter
_handlersAdded = False
Exit Sub
End If
If Not _handlersAdded Then
AddHandler dgv.DragEnter, AddressOf DragEnter
_handlersAdded = True
End If
Next
End Sub