Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing AddressOf to a function in VB.NET to use AddHandler

I need to pass a reference of a function to another function in VB.NET. How can this be done?

My function needs to use AddHandler internally, for which I need to pass it a handling function. My code below obviously does not work, but it conveys the idea of what I need.

Public Function CreateMenuItem(ByVal Name As String, ByRef Func As AddressOf ) As MenuItem
   Dim item As New MenuItem

   item.Name = Name
   'item.  other options

   AddHandler item.Click, AddressOf Func

   Return item
End Function

Is there another way to do this? The AddHandler needs to be set to a passed parameter in a function somehow...

like image 252
DieSlower Avatar asked May 24 '13 17:05

DieSlower


2 Answers

A function delegate is just what you need to do this. First you need to define the delegate somewhere in the class. Change the signature to fit your event of course.

Public Delegate Sub MyDelegate(sender As System.Object, e As System.EventArgs)

Your function will take the delegate as an argument.

Public Function CreateMenuItem(ByVal Name As String, del As MyDelegate) As MenuItem
  ''''
  AddHandler item.Click, del
  ''''
End Function

Public Sub MyEventHandler(sender As System.Object, e As System.EventArgs)
  ''''
End Sub

And here's how you call the function:

CreateMenuItem(myString, AddressOf MyEventHandler)
like image 85
Fuzhou Hu Avatar answered Oct 08 '22 16:10

Fuzhou Hu


Your second argument in the function should be of type EventHandler, and your function would then look like:

Public Function CreateMenuItem(ByVal Name As String, ByRef Func As EventHandler) As MenuItem
    Dim item As New MenuItem

    item.Name = Name
    'item.  Other options

    AddHandler item.Click, Func

    Return item
End Function

Now you need a method to handle those clicks:

Private Sub ItemClick(sender As Object, e As EventArgs)
    'Do something with that click here
End Sub

And you can consume those two methods now with something like:

    Dim handler = New EventHandler(AddressOf ItemClick)
    Dim i = CreateMenuItem("My item", handler)

    i.PerformClick()
like image 27
Janez Lukan Avatar answered Oct 08 '22 15:10

Janez Lukan