Maddy Maddy - 5 months ago 12
Vb.net Question

How to assign values to the delegate function in VB.NET

I have a delegate function in another class, which is shown below

Public Class Connect

Public Delegate Function RP_ClientConnect(ByVal hwndClient As IntPtr, _
ByVal deviceID As Short, _
ByVal protocol As String) As Short


I have a function in which I am trying to assign the values to the delegate function. But I am not sure of how to do that. I tried but couldn't able to resolve it.

I am trying to pass the new values for deviceID and protocol in delegate function.

Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click

Dim myNewClientConnect As Connect
Dim iDNumber as Integer= 10
Dim prot as String = "CAN"
myNewClientConnect(Nothing, iDNumber, prot)

End Sub


I am new to vb.Net and expecting to get few suggestions from you people.

Answer

You're not calling the delegate, you're calling the constructor of your class.

First, Create a method with the same signature as the delegate:

Private Function MyDelegate(ByVal hwndClient As IntPtr, _
                            ByVal deviceID As Short, _
                            ByVal protocol As String) As Short
    'Do something.
End Function

Then define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.

Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
    ' Create an instance of the delegate.
    Dim d As RP_ClientConnect = AddressOf MyDelegate
    ' Call the method.
    d.Invoke(Nothing, iDNumber, prot)
End Sub

You can refer to this MSDN page for more details.

Comments