To create a new event handler on a control you can do this
c.Click += new EventHandler(mainFormButton_Click);
or this
c.Cli
Sometimes we have to work with ThirdParty controls and we need to build these awkward solutions. Based in @Anoop Muraleedharan answer I created this solution with inference type and ToolStripItem support
public static void RemoveItemEvents(this T target, string eventName)
where T : ToolStripItem
{
RemoveObjectEvents(target, eventName);
}
public static void RemoveControlEvents(this T target, string eventName)
where T : Control
{
RemoveObjectEvents(target, eventName);
}
private static void RemoveObjectEvents(T target, string Event) where T : class
{
var typeOfT = typeof(T);
var fieldInfo = typeOfT.BaseType.GetField(
Event, BindingFlags.Static | BindingFlags.NonPublic);
var provertyValue = fieldInfo.GetValue(target);
var propertyInfo = typeOfT.GetProperty(
"Events", BindingFlags.NonPublic | BindingFlags.Instance);
var eventHandlerList = (EventHandlerList)propertyInfo.GetValue(target, null);
eventHandlerList.RemoveHandler(provertyValue, eventHandlerList[provertyValue]);
}
And you can use it like this
var toolStripButton = new ToolStripButton();
toolStripButton.RemoveItemEvents("EventClick");
var button = new Button();
button.RemoveControlEvents("EventClick");