AddHandler RemoveHandler Question

H

hartley_aaron

Hi,

I was trying to store the address of the my current handler for a
particular event so as to simplify using AddHandler and RemoveHandler
throughout my code. However, I cannot seem to get any kind of variable
to except the data. When I tried a Long I got the message "'AddressOf'
expression cannot be converted to 'Long' because 'Long' is not a
delegate type." I tried other datatypes as well but was not able to
find anything that worked. Here is a very simply example of what I am
trying to do:


Dim CurrentHandler as Long

....

RemoveHandler MyObject.SomethingHappens, CurrentHandler
CurrentHandler = AddressOf DoThis
AddHandler MyObject.SomethingHappens, CurrentHandler

....

RemoveHandler MyObject.SomethingHappens, CurrentHandler
CurrentHandler = AddressOf DoThat
AddHandler MyObject.SomethingHappens, CurrentHandler

....

RemoveHandler MyObject.SomethingHappens, CurrentHandler
CurrentHandler = AddressOf DoSomethingElse
AddHandler MyObject.SomethingHappens, CurrentHandler
 
M

Marina

Right. You are trying to convert what is essentially a function pointer, to
other types. That can't work.

You need to declare your own delegate type, which is to say a delegate that
can point to a method with a specified signature. Then, you can use it.

Something like:

Public Delegate Sub MyDelegateType(ByVal int1 As Integer)
Public Sub MySub(ByVal myIntParam As Integer)
' Do Stuff Here
End Sub
Public Sub MainCodeSub()
Dim savedPointer As MyDelegateType = AddressOf MySub
End Sub
 
P

Patrick Philippot

When I tried a Long I got the message
"'AddressOf' expression cannot be converted to 'Long' because 'Long'
is not a delegate type."

Hi,

If you look at the documentation relative to AddressOf, you'll see that
AddressOf returns a Delegate object. So your variable should be of type
Delegate.

Dim CurrentHandler as [Delegate]

(the brackets are here because Delegate is also a reserved keyword).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top