Home > OS >  How to get click event handler names of ToolStripDropDownItem?
How to get click event handler names of ToolStripDropDownItem?

Time:11-19

I have a old project in Windows Forms which has more than 300 menus with menu click events throughout the MDI form. Is there any way to get the click event names in strings (e.g. "toolStripMenuItem_Click")? I tried like this,

foreach (ToolStripMenuItem menu in menuStrip.Items)
{
   foreach (ToolStripDropDownItem submenu in menu.DropDownItems)
   {
       var _events= submenu.GetType()
                     .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
                     .OrderBy(pi => pi.Name).ToList();
   }
}

But it always returns empty. What is correct way to achieve this?

CodePudding user response:

Retrieving event handlers at runtime is not easy especially within the Forms framework where some events have special handling in the background.

A simpler approach (if you don't need the names at runtime but at design time) is to use regular expressions on your MyForm.designer.cs file to extract the names of the click handlers.

See this sample source:

private void button1_Click(object sender, EventArgs e)
{
    string fileLocaton = @"C:\Users\nineb\source\repos\WindowsFormsApp37\WindowsFormsApp37\Form1.Designer.cs";
    string fileContent = File.ReadAllText(fileLocaton);

    // Find all menu items in the designer file
    var matches = Regex.Matches(fileContent, @"System\.Windows\.Forms\.ToolStripMenuItem (. ?)\;");
    foreach (Match match in matches)
    {
        string menuName = match.Groups[1].Value;
        textBox1.AppendText("Menuitem "   menuName   Environment.NewLine);

        // For each menu item, find all the event handlers
        var clickMatches = Regex.Matches(fileContent, 
            @"this\."   Regex.Escape(menuName)   @"\.Click \ \= new System\.EventHandler\(this\.(. ?)\)\;");
        foreach (Match clickMatch in clickMatches)
        {
            string handlerName = clickMatch.Groups[1].Value;
            textBox1.AppendText("Eventhandler "   handlerName   Environment.NewLine);
        }
    }
}
  • Related