Jump to content
  • Advertisement
Sign in to follow this  
DrGUI

[.net] Hooking event multiple times

This topic is 4492 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!