winform获取窗体所有控件

以下图中的控件来比较这两种方式获取控件的方式:

1. 最简单的方式:

private void GetControls1(Control fatherControl)
{
    Control.ControlCollection sonControls = fatherControl.Controls;
    //遍历所有控件
    foreach (Control control in sonControls)
    {
        listBox1.Items.Add(control.Name);
    }
}

 

获取的结果显示在右侧的ListBox中,可以发现没有获取到Panel、GroupBox、TabControl等控件中的子控件。

2. 在原有方式上增加递归:

private void GetControls1(Control fatherControl)
{
    Control.ControlCollection sonControls = fatherControl.Controls;
    //遍历所有控件
    foreach (Control control in sonControls)
    {
        listBox1.Items.Add(control.Name);
        if (control.Controls != null)
        {
            GetControls1(control);
        }
    }
}

 

 

 

绝大多数控件都被获取到了,但是仍然有两个控件Timer、ContextMenuStrip没有被获取到。

3. 使用反射(Reflection):

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

 

转载于CSDN博主「NovenBae」
原文链接:https://blog.csdn.net/softimite_zifeng/article/details/54289012

分类:

发表评论