Sign in to follow this  
DrGUI

[.net] Hooking event multiple times

Recommended Posts

Hey When you add the same event handler more than once does that mean the target would be called more than once upon invocation? Here's my example:
public void Acquire()
{
	m_InputControl.KeyPress += new System.Windows.Forms.KeyPressEventHandler(m_InputControl_KeyPress);
}
If the keyboard was acquired more than once I don't want this to have the effect of the handler being called multiple times.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
yes it would invoke multiple times.

An easy way to avoid this:
try to remove the delegate before adding.

public void Acquire()

{
m_InputControl.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(m_InputControl_KeyPress);
m_InputControl.KeyPress += new System.Windows.Forms.KeyPressEventHandler(m_InputControl_KeyPress);

}

Share this post


Link to post
Share on other sites
Thank youuuu, AP.

That solves my problem, but it seems a bit strange how you remove delegates like that although a new one is being created with the 'new' keyword!

Share this post


Link to post
Share on other sites
It may look strange but this is the "official" way to do it. It is necessary to create a new handler because the old is already added and you can’t access it anymore. The new handler is used to find the old one in the event. After this it will remove the old one from the list. At last the garbage collector will destroy both handlers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this