Handling Events By Attaching a Delegate

Posted by Chikul under Windows Forms category on | Views : 1514
Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.
The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

In Other Word :

A Delegate is a function whose job is to Respond to an function.
A Delegate Has three Parts :
1. AddHandler :
It is a Visual basic .Net Key word.
2. Me.MouseDown :
It is the name of the event
3. frmDelegates_MouseDown :
It Is the name of a delegate to handel the event

'Handling Events By Attaching a Delegate

'Code for Delegate
Public Class frmDelegates

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

'Attach a 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_MouseDown
End Sub

End Class

Comments or Responses

Login to post response