中获取winform中的所有子菜单项

中获取winform中的所有子菜单项

本文介绍了无法在c#中获取winform中的所有子菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有菜单栏的 winform,如下所示:

I have a winform with menu bar like this :

File==>Add==>New Project
File==>Add==>Existing Project
File==>Open
File==>Exit
Edit==>Copy
Edit==>Cut
Help==>View Help
Help==>About

我想获取所有菜单项和子菜单项的文本.
我试过这个代码:

I want to get the text of all menu items and submenu items.
I have tried this code :

for (int i = 0; i < menuStrip1.Items.Count; i++)
{
foreach (ToolStripMenuItem item in ((ToolStripMenuItem)menuStrip1.Items[i]).DropDownItems)
{
  textBox1.Text += item.OwnerItem.Text + @"==>" + item.Text + Environment.NewLine;
}
}

结果为:

 File==>Add
 File==>Open
 File==>Exit
 Edit==>Copy
 Edit==>Cut
 Help==>View Help
 Help==>About

正如它显示的那样,它没有显示所有子菜单项.我试过这个代码:

as it shows it does not show all of submenu items. I have tried this code :

for (int i = 0; i < menuStrip1.Items.Count; i++)
{
  for (int j = 0; j < ((ToolStripMenuItem) menuStrip1.Items[i]).DropDownItems.Count; j++)
  {
     foreach (ToolStripMenuItem item in (ToolStripMenuItem)menuStrip1.Items[i]).DropDownItems[j]))
     {
      textBox1.Text += item.OwnerItem.Text + @"==>" + item.Text + Environment.NewLine;

      }
   }
}

但它给出了这个错误:

foreach statement cannot operate on variables of type 'System.Windows.Forms.ToolStripItem' because 'System.Windows.Forms.ToolStripItem' does not contain a public definition for 'GetEnumerator'



注意:我正在寻找一个通用的解决方案(针对任意数量的菜单项和任意数量的嵌套子菜单项),而不仅仅是针对这个问题.

提前致谢.

Note : I am looking for a general solution(for the arbitrary number of menu item and arbitrary number of nested sub menu items) not only for this problem.

Thanks in advance.

推荐答案

使用 recursion .

编写一个调用自身的方法(但也会检查终止,因此在不需要深入研究时它不会调用自身).

Write a method that calls itself (but checks for termination as well so it does not call itself when not needed to go deeper).

这是一些代码:

static string GetText2(ToolStripMenuItem c)
{
    string s = c.OwnerItem.Text + @"==>" + c.Text + Environment.NewLine;
    foreach (ToolStripMenuItem c2 in c.DropDownItems)
    {
        s += GetText2(c2);
    }
    return s;
}

这篇关于无法在c#中获取winform中的所有子菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:00