Capturing the entire ToolStripMenu tree with ToString
If I run the code in different areas of my menu tree, I only get one item, how would you first apply this logic to all the subcomponents of that menu tree, and secondly, illustrate the whole tree.
In the code I am showing only 1 stage of each used area
MessageBox.Show((ToolStripMenuItem).ToString());
So the above will only show File or Save or Open and not File Open or File Save.
Should I use foreach with my toolstripmenuitem?
source to share
Let's say I have MenuStrip
a ToolStripMenuItem
named fileToolStripMenuItem
(with text File
), which are sub-items New
and Open
. It also Open
has From file
and Recent
. To access everyone File
ToolStripMenuItems
(that's the kids) you need a recursive method that goes through all the levels (for accessing the kids, grandchildren ...)
private IEnumerable<ToolStripMenuItem> GetChildToolStripItems(ToolStripMenuItem parent)
{
if (parent.HasDropDownItems)
{
foreach (ToolStripMenuItem child in parent.DropDownItems)
{
yield return child;
foreach (var nextLevel in GetChildToolStripItems(child))
{
yield return nextLevel;
}
}
}
}
This method takes a first level menu item and returns IEnumberable<ToolStripMenuItem>
sou, after which you can iterate over it (to get a name, change a property, etc.).
Use it like this:
var list = GetChildToolStripItems(fileToolStripMenuItem);
In my example, this will return you to a set of sub-elements, such as: New, Open, From File, Recent
.
You can easily browse the collection and get the text of the item (to display in MessageBox
, for example:
MessageBox.Show(string.Join(", ", list.Select(x=>x.Text).ToArray()))
or, if you like, for example:
foreach (ToolStripMenuItem menuItem in list)
{
MessageBox.Show(string.Format("item named: {0}, with text: {1}", menuItem.Name, menuItem.Text));
}
EDIT : After I saw the comment that the OP's idea is to get all items from MenuStrip
, here's an example of that.
I wrote an additional method that takes MenuStrip
as a parameter, iterates through everything ToolStripMenuItems
and calls the method for each item GetChildToolStripItems
. Returns a list of all top-level items and all children and children ...
private List<ToolStripMenuItem> GetAllMenuStripItems(MenuStrip menu)
{
List<ToolStripMenuItem> collection = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menu.Items)
{
collection.Add(item);
collection.AddRange(GetChildToolStripItems(item));
}
return collection;
}
using:
var allItems = GetAllMenuStripItems(menuStrip1)
Hope it helps.
source to share