Justin
Justin

Reputation: 972

Loop Through Menu Items in MDI Parent Form in WinForms

I need a way to loop through the menu items in a MDI Parent Form.

The reason why is because I am setting the background of the buttons when they are activated to show the user which ones they have selected.

The pictures below illustrates an example of System Settings being selected in the menu and the child form shown on the right.

Currently I achieve this using direct code:

systemManagementToolStripMenuItem.BackColor = Color.Gray;

enter image description here

How can I loop through so that each time I click on a menu item it will change the background colour of the selected item.

Upvotes: 1

Views: 733

Answers (1)

KDecker
KDecker

Reputation: 7148

Just collect the ToolStipMenuItems into a List and loop over the list whenever the user performs the action to initiate the looping.

// First create the list of menu items
int selectedMenuItem = 0;
List<ToolStripMenuItem> menuItems = new List<ToolStripMenuItem>();
menuItems.Add(systemManagementToolStripMenuItem);

// When the user performs some action, such as pressing down arrow
selectedMenuItem = (selectedMenuItem + 1) % menuItems.Count;
UpdateSelectedItems();

// Have some method to update the buttons
public void UpdateSelectedItems()
{
    foreach(var item in menuItems)
        item.BackColor = Color.DarkGray;
    menuItems[selectedMenuItem].BackColor = Color.Gray;
}

Upvotes: 1

Related Questions