.Net Winform setting click event for all ToolStrip Items and MenuStrip Items

I wanted to run all click event through one method. That way I can update them as needed as well as call them from other places in the code.

After looking around I was able to use the following:

My form has a ToolStrip and a MenuStrip.

public Form1()
{
    InitializeComponent();
 
    // Get All Menu Items and all Tool Strip Buttons into a list
    var toolStripItems = toolStrip1.Items.OfType<ToolStripItem>().ToList().Union(menuStrip1.Items.GetAllToolStripMenuItems().OfType<ToolStripItem>()).ToList();
    // Set All Click Events for controls
    toolStripItems.ForEach(i => i.Click += Item_Click);
}
 
private void Item_Click(object sender, EventArgs e)
{
    ProcessMenuItem((sender as ToolStripItem).Text);
}
 
private void ProcessMenuItem(string menuItem)
{
    switch (menuItem)
    {
        case "&New":
            break;
        case "E&xit":
            Application.Exit();
            break;
    }
}

Extension Method:

public static class Extensions
{
    public static IEnumerable<ToolStripMenuItem> GetAllToolStripMenuItems(this ToolStripItemCollection toolStripItemCollection)
    {
        var toolStripMenuItems = new List<ToolStripMenuItem>();
        foreach (var toolStripItem in toolStripItemCollection.OfType<ToolStripMenuItem>())
        {
            toolStripMenuItems.Add(toolStripItem);
            toolStripMenuItems.AddRange(GetAllToolStripMenuItems(toolStripItem.DropDownItems));
        }
        return toolStripMenuItems;
    }
}

By using the above it becomes very straight forward to add what is needed by a click event.

All ToolStripItems are wired up to use and just by adding the text to the ProcessMenuItem method and the code that is needed to execute it makes it pretty straight forward to add the needed code.

Comments are closed.