C# WinForm遍历窗体控件的3种方法

转  https://www.cnblogs.com/zhaoshujie/p/14638460.html

1.循环遍历

private void GetControls(Control fatherControl)
{
    Control.ControlCollection sonControls = fatherControl.Controls;
    foreach (Control control in sonControls)
    {
        listBox1.Items.Add(control.Name);
    }
}

结果:能获取到Panel、GroupBox、TabControl等控件
问题:Panel等控件上面的子控件获取不到

2.递归遍历

private void GetControls(Control fatherControl)
{
    Control.ControlCollection sonControls = fatherControl.Controls;
    foreach (Control control in sonControls)
    {
        listBox1.Items.Add(control.Name);
        if (control.Controls != null)
        {
            GetControls(control);
        }
    }
}

结果:能获取到绝大多数控件
问题:Timer、ContextMenuStrip等控件获取不到

3.使用反射

private void GetControls(Control fatherControl)
{
    System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    for (int i = 0; i < fieldInfo.Length; i++)
    {
        listBox1.Items.Add(fieldInfo[i].Name);
    }
}

结果:所有控件都被获取到了

DevExpress控件无法使用this.Controls进行遍历,只能通过反射的方法获得,如下代码:

public void SearchBarManager()
{
    Type FormType = this.GetType();
    FieldInfo[] fi = FormType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
    foreach (FieldInfo info in fi)
    {
        if (info.FieldType == typeof(DevExpress.XtraBars.BarManager))
        {
            DevExpress.XtraBars.BarManager bar = (info.GetValue(this)) as DevExpress.XtraBars.BarManager;
            foreach (DevExpress.XtraBars.BarItem bi in bar.Items)
            {
                MessageBox.Show(bi.Name);
            }
        }
    }
}

posted on 2021-12-01 13:58  _ali  阅读(1546)  评论(0编辑  收藏  举报

导航