Resolved Obtain the event handlers of a given ToolStripMenuItem

aaaron

Well-known member
Joined
Jan 23, 2011
Messages
216
Programming Experience
10+
The Component class has a property called Events that returns an EventHandlerList which provides the list of event handlers which can be used to get the event handlers for a control.

However, the ToolStripMenuItem does not inherit Component Control so I can't use that.

I been looking for a similar way to obtain the event handlers of a given ToolStripMenuItem but have been unabe to do so.

I it possible?
 
Last edited:
Solution
This works for me in .Net 8, can copy all event handlers for any component, controls and menu items alike.
VB.NET:
Private Sub CopyEvents(source As Component, target As Component)
    Dim info = GetType(Component).GetProperty("Events", BindingFlags.NonPublic Or BindingFlags.Instance)
    Dim list1 = DirectCast(info.GetValue(source), EventHandlerList)
    Dim list2 = DirectCast(info.GetValue(target), EventHandlerList)
    list2.AddHandlers(list1)
End Sub
Look at the event. There seems to be problem with Source Browser at the moment, but here is the source at Github for ToolStripItem.Click event where you see the field name used as key to add/remove event handler: winforms/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs at main · dotnet/winforms
C#:
 add => Events.AddHandler(s_clickEvent, value);
Also each event has a protected On* method that raises the event, here there OnClick: winforms/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripItem.cs at 5207c6554bb20236bd91c6083c3e1ee3c76c9402 · dotnet/winforms
C#:
RaiseEvent(s_clickEvent, e);
There's also the ILSpy app at Microsoft Store to browse .Net source code. Like Source Browser (when it is working), and unlike the Github source, you can click members and types to easily navigate through the sources.
 
Back
Top