I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (Alt + Down) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...
How do I raise the event from an external function via reflection?
From Raising an event via reflection, although I think the answer in VB.NET, that is, two posts ahead of this one will provide you with the generic approach (for example, I'd look to the VB.NET one for inspiration on referencing a type not in the same class):
It seems that the code from the accepted answer by Wiebe Cnossen could be simplified to this one liner:
Here's a demo using generics (error checks omitted):
I wrote an extension to classes, which implements INotifyPropertyChanged to inject the RaisePropertyChange<T> method, so I can use it like this:
without implementing the method in any base class. For my usage it was to slow, but maybe the source code can help someone.
So here it is:
I removed some parts of the original code, so the extension should work as is, without references to other parts of my library. But it's not really tested.
P.S. Some parts of the code was borrowed from someone else. Shame on me, that I forgot from where I got it. :(
In general, you can't. Think of events as basically pairs of
AddHandler
/RemoveHandler
methods (as that's basically what what they are). How they're implemented is up to the class. Most WinForms controls useEventHandlerList
as their implementation, but your code will be very brittle if it starts fetching private fields and keys.Does the
ButtonEdit
control expose anOnClick
method which you could call?Footnote: Actually, events can have "raise" members, hence
EventInfo.GetRaiseMethod
. However, this is never populated by C# and I don't believe it's in the framework in general, either.You can't normally raise another classes events. Events are really stored as a private delegate field, plus two accessors (add_event and remove_event).
To do it via reflection, you simply need to find the private delegate field, get it, then invoke it.