Detaching an event Hadler Using "RemoveHandler"

Chikul
Posted by Chikul under Windows Forms category on | Views : 3757
We can Detach an event handler from an event using the "RemoveHandler" Key word.
Its Syntax is Similar to "AddHandler"
This is basically used to Remove Handler at run time when its not necessary

Here for one event (MouseDown) First & Second delegates will get fire, Not the Third one

Public Class frmDelegates

'First Delegate to handel the MouseDown event
Sub frmDelegates_MouseDown1(ByVal sender As Object, ByVal e As MouseEventArgs)
MessageBox.Show("First Delegate Executed", String.Format("the {0} Mouse Button hit me at : ", e.Button.ToString()))
End Sub

'Second Delegate to handel the MouseDown event
Sub frmDelegates_MouseDown2(ByVal sender As Object, ByVal e As MouseEventArgs)
MessageBox.Show("Second Delegate Executed", String.Format("the {0} Mouse Button hit me at : ", e.Button.ToString()))
End Sub

'Third Delegate to handel the MouseDown event
Sub frmDelegates_MouseDown3(ByVal sender As Object, ByVal e As MouseEventArgs)
MessageBox.Show("Third Delegate Executed", String.Format("the {0} Mouse Button hit me at : ", e.Button.ToString()))
End Sub

'Attach Multiple Delegate for the event
Private Sub frmDelegates_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler Me.MouseDown, AddressOf frmDelegates_MouseDown1
AddHandler Me.MouseDown, AddressOf frmDelegates_MouseDown2
RemoveHandler Me.MouseDown, AddressOf frmDelegates_MouseDown3
End Sub

End Class

Comments or Responses

Login to post response