I am trying to use Reflection to add a method from a class to an event. Here is my setup.
- Have a class with a keyPressDown & keyPressUp method. I also have an Event in this class. keyPressDown & keyPressUp will fire whatever methods are subscribed to it (if any).
These additional methods are controlling RGB light emitting diodes. One method can flash a color, another can fade a color, etc..
I can subscribe to the event like myEventKeyUp += myClass.MethodA;
My problem is, I am storing the configuration the user wants in a database. So the only thing I can think of is storing the Method Name as text and use reflection to add it to the event handler.
Code Example:
Class MyClass
public event delegateKeyDown keyDownEvent;
public event delegateKeyUp keyUpEvent;
public void KeyUp()
{
joystick.SetBtn(false, 1, vJoyButtonID);
if (keyUpEvent != null) keyUpEvent();
}
public void KeyDown()
{
joystick.SetBtn(true, 1, vJoyButtonID);
// IF WE HAVE ANY LISTENERS THEN FIRE THEM
if (keyDownEvent != null) keyDownEvent();
}
public void MethodA()
{
// DO SOMeTHING HERE
}
Main Form
button.keyDownEvent += button.SetRandomColor;
button.keyUpEvent += button.TurnOff;
What I need to do is something like: button.keyUpEvent += MyClass.GetType().GetMethod("MethodA");
I know you can't do what I am trying to do with Reflection, I read that I can use reflection to get hold of the delegate that contains the event handler, and add it through that way but I am unsure (or unclear about this).