Associating toolbar buttons and menus
In my good ol' MFC days, I remember being able to associate the actions for menus to be executed when a toolbar button was clicked as well. Nowadays, when I am doing my amateur coding in C# winforms, I could not find one example of similar behavior in .NET. I am sure there were ways but I just could not find them. So, like any other developer, I found my own.
Basically, I associated one event handler with the whole toolbar. Then, I made the Tag value of the toolbar buttons to contain the menu item name with with they are associated with ( I could have made the the references to menu items itself, but that would have meant needing to go into code and hack that code. Now you can do this just in the toolbar button collection editor in UI). When any button is clicked, I use the tag and a bit of reflection to execute the menu item to be executed.
Is this how others do it? I wonder. I have started venturing into winforms recently so, I am not sure if I right.. or not..
private void tlbMain_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
{
//We will always get this.
Object o = e.Button.Tag;
if ( o != null)
{
string sMenu = o.ToString();
ExecMenuItem(sMenu);
}
}
private void ExecMenuItem(string sMenu)
{
System.Reflection.FieldInfo fMenu =
this.GetType().GetField(sMenu,System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.NonPublic);
MenuItem m = fMenu.GetValue(this) as MenuItem;
if (m != null)
{
m.PerformClick();
}
}