通过MenuStrips迭代

时间:2017-12-27 09:40:06

标签: c# winforms controls

我找到了迭代menustrip项目的答案,但没有运气来迭代menuStrips(假设我在表单中有一些contextMenuStrip)。

foreach(Control c in this.Controls)
{ 
    if(c is ContextMenuStrip)
    {
        // This doesn't work. I figured out contextmenustrips are not
        // holding in this.Controls
    }
}

3 个答案:

答案 0 :(得分:1)

foreach(var ctrl in this.components.Components)
{
    if (ctrl is ContextMenuStrip ctx)
    {
        MessageBox.Show(ctx.GetType().Name);
    }
}

答案 1 :(得分:1)

如果您需要以任何形式使用此表单,则需要使用反射访问其私有字段。因为ContextMenuStrip是私有成员。 这是一种适用于任何给定形式的方法:

process(L1, [H2|T2], [H2|T], Inconsistent):-
    H2 = [Name, Number, _Info],
    elementInList(L1, [Name, Number]),
    process(L1, T2, T, Inconsistent).
process(L1, [H2|T2], Consistent, [H2|T]):-
    H2 = [Name, Number, _Info],
    \+ elementInList(L1, [Name, Number]),
    process(L1, T2, Consistent, T).
process(_L1, [], [], []).

elementInList([H|T], H).
elementInList([H|T], E):-
    elementInList(T, E).

答案 2 :(得分:1)

ContextMenuStrips是组件的一部分,而不是控件。

foreach(var c in components.Components)
{ 
   if(c is ContextMenuStrip)
   {
   }
}

OR

 ContextMenuStrip cStrip = null;    
 foreach(var c in components.Components)
 { 
   cStrip = c as ContextMenuStrip;
   if(cStrip!=null)
   {
   }
 }