C # Clear the original event handler in others' controls

Source: Internet
Author: User

Sometimes we use others' controls, but this control itself has attached an event handler to DoubleClick. For example, when we double-click this control, a form will pop up, but we do not want this form, but we cannot use DoubleClick-= ...... This event handler is written by someone else and is not in our code. How can we get rid of the original DoubleClick handler at this time?

Assume that the control class we use is testcontrol, and an instance is testcontrol1. The control itself has a DoubleClick processing method, which is a pop-up form. In this case, I want to block it. You can do this:

Type t = typeof (testControl); // or Type t = testControl1.GetType (); PropertyInfo propInfo = t. getProperty ("Events", BindingFlags. instance | BindingFlags. nonPublic); EventHandlerList eventHandlers = (EventHandlerList) propInfo. getValue (testControl1, null); FieldInfo fieldInfo = typeof (Control ). getField ("EventDoubleClick", BindingFlags. static | BindingFlags. nonPublic); Delegate del = eventHandlers [fieldInfo. getVa Lue (testControl1)]; if (del! = Null) {foreach (Delegate temp in del. getInvocationList () {eventHandlers. removeHandler (fieldInfo. getValue (null), temp) ;}/// add our own event handler testControl1.DoubleClick + = new EventHandler (testControl1_DoubleClick) for this event );

 

OK!

 

Another method:

Type t = m_MapService.GetType (); // or Type t = testControl1.GetType ();

FieldInfo finfo = t. GetField ("OnZBST", BindingFlags. NonPublic | BindingFlags. Instance );
Delegate instanceDelegate = finfo. GetValue (m_MapService) as Delegate;
EventInfo eve = t. GetEvent ("OnZBST ");
Foreach (Delegate d in instanceDelegate. GetInvocationList ())
{
Eve. RemoveEventHandler (m_MapService, d );
}

I thought I was using it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.