0

I have a UserControl, named FormDesignerControl. FormDesignerControl has a number of public events on it, declared thus:

public event EventHandler LeftMouseClick;
public event EventHandler LeftMouseDownInControl;
public event EventHandler LeftMouseMoveInControl;
public event EventHandler LeftMouseUpInControl;

public event EventHandler LeftMouseDownInThumb;
public event EventHandler LeftMouseMoveInThumb;
public event EventHandler LeftMouseUpInThumb;

public event EventHandler RightMouseClick;
public event EventHandler RightMouseDownInControl;
public event EventHandler RightMouseMoveInControl;
public event EventHandler RightMouseUpInControl;

At one point, I pass an instance of FormDesignerControl from one place in my program to another and want to all the handlers. I do not have access to the original events. Basically, I need to clear the current settings of the event handlers. Ideally what I'd like to do is this:

FormDesignerControl oFDC = new FormDesignerControl();

// some code occurs manipulating oFDC and setting the events on it, and then at some point...

oFDC.LeftMouseClick.Clear(); // but this isn't facilitated
oFDC.LeftMouseClick += myNewEventCode;

It seems the only way to do this is to have access to the original events so as to be able to use the -= operator.

Is there a way to clear an arbitrary event from an arbitrary object, perhaps using System.Reflection even if I have to encapsulate it in a method? Something like this:

void ClearEvent(object obj, string eventName)
Mark Roworth
  • 409
  • 2
  • 15
  • Already answered on here https://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-an-event – stefan_aus_hannover Jun 29 '21 at 15:51
  • The code there doesn't appear to work with any event for any object, only Button clicks on form controls. I've tried using it and it errors. I have found a generic solution, though, here: https://www.codeproject.com/Articles/103542/Removing-Event-Handlers-using-Reflection which appears to work irrespective of class or event. – Mark Roworth Jun 29 '21 at 16:35

1 Answers1

0

Generic (and very neat, I might say) solution to remove any event handler from any object found. Single line solution here: https://www.codeproject.com/Articles/103542/Removing-Event-Handlers-using-Reflection

EventHanderHelper.RemoveEventHandler(oFDC, "LeftMouseClick");
Mark Roworth
  • 409
  • 2
  • 15