Sign in to follow this  

[.net] Hooking event multiple times

This topic is 4274 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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

This topic is 4274 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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