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

2021-05-16 02:28

阅读:487

标签:oid   panel   val   exp   orm   flags   info   i++   collect   

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 

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

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);
            }
        }
    }
}

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

标签:oid   panel   val   exp   orm   flags   info   i++   collect   

原文地址:https://www.cnblogs.com/zhaoshujie/p/14638460.html


评论


亲,登录后才可以留言!