I'm going to assume that you need recursion, that your menu structure could have more than one level of nesting, like this:
Form1
Form5
Form6
Form2
Form7
Form8
Form11
Form12
Form13
Form9
Form3
Form4
Form10
Code example: assume a main form, MainForm, on MainForm a ToolMenuStrip, menuStrip1, and a Button 'btnBuildTree.
private Dictionary<TreeNode, ToolStripMenuItem> dctTSMenuToTNode;
private void MainForm_Load(object sender, EventArgs e)
{
dctTSMenuToTNode = new Dictionary<treenode,>();
}
private void btnBuildTree_Click(object sender, EventArgs e)
{
dctTSMenuToTNode.Clear();
buildTree(menuStrip1.Items, treeView1.Nodes);
}
private void buildTree(ToolStripItemCollection menuItems, TreeNodeCollection tNodes)
{
foreach (ToolStripMenuItem menuItem in menuItems)
{
menuItem.Visible = true;
var newNode = new TreeNode(menuItem.Text);
tNodes.Add(newNode);
newNode.Name = (newNode.Level == 0)
? "x"
: "X";
dctTSMenuToTNode.Add(newNode, menuItem);
if (menuItem.HasDropDownItems)
{
buildTree(menuItem.DropDownItems, newNode.Nodes);
}
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNode currentNode = e.Node;
MessageBox.Show(string.Format("Node: {0} Name: {1}", dctTSMenuToTNode[currentNode].Text, currentNode.Name));
switch (dctTSMenuToTNode[currentNode].Text)
{
case "Form1":
break;
}
}
Comments:
1. While this will work (try it): a better strategy would be to use a Dictionary where the Key Type is 'TreeNode, and the Value Type of the Key is 'Form a reference to each instance of the various Forms you create.
2. Curious question: why do you need both a TreeView and a Menu based representation of your App's Forms structure ?