I would like to create a method that takes an event as an argument and adds eventHandler to it to handle it properly. Like this:
I have two events:
public event EventHandler Click; public event EventHandler Click2;
Now I would like to pass a particular event to my method like this (pseudocode):
public AttachToHandleEvent(EventHandler MyEvent) { MyEvent += Item_Click; } private void Item_Click(object sender, EventArgs e) { MessageBox.Show("lalala"); } ToolStripMenuItem tool = new ToolStripMenuItem(); AttachToHandleEvent(tool.Click);
Is it possible?
I've noticed that this code worked fine, and returned to my project and noticed that when I pass an event declared in my class, it works, but when I pass event from other class it still does not work.
What I get is this error:
The event 'System.Windows.Forms.ToolStripItem.Click' can only appear on the left hand side of += or -=
To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .
Event handlers are methods in an object that are executed in response to some events occurring in the application. To understand the event handling model of . Net framework, we need to understand the concept of delegate.
My original answer was suitable from within the class that defined the event, but you've since updated your question to reflect that you wish to accomplish this from outside the defining class, so I've stricken that.
Only the class that defines an event can refer to the implicit delegate variable that the event uses. From outside that class, you only have access to the add
and remove
methods, via +=
and -=
. This means that you can't do what you're asking, directly. You can, however, use a functional approach.
class A{ public event EventHandler Event1; public void TriggerEvent1(){ if(Event1 != null) Event1(this, EventArgs.Empty); } } class B{ static void HandleEvent(object o, EventArgs e){ Console.WriteLine("Woo-hoo!"); } static void AttachToEvent(Action<EventHandler> attach){ attach(HandleEvent); } static void Main(){ A a = new A(); AttachToEvent(handler=>a.Event1 += handler); a.TriggerEvent1(); } }
I did it like this:
public AttachToHandleEvent(Object obj, string EventName) { EventInfo mfi = obj.GetType().GetEvent(EventName); MethodInfo mobj = mfi.GetAddMethod(); mobj.Invoke(obj, new object[] { Item_Click}); } private void Item_Click(object sender, EventArgs e) { MessageBox.Show("lalala"); } ToolStripMenuItem tool = new ToolStripMenuItem(); AttachToHandleEvent(tool "Click");
Thank you all for advice. This solution could not be done without your help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With