mardi 29 juin 2021

C# How to clear handlers from custom events

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)




Aucun commentaire:

Enregistrer un commentaire