Winform遍历窗口的所有控件(几种方式实现)

C#遍历窗体所有控件或某类型所有控件

//遍历窗体所有控件,
foreach (Control control in this.Controls)
{
    //遍历后的操作...
    control.Enabled = false;
}
遍历某个panel的所有控件

foreach (Control control in this.panel4.Controls)
{
    control.Enabled = false;
}
遍历所有TextBox类型控件或者所有DateTimePicker控件

复制代码
foreach (Control control in this.Controls)
{
  //遍历所有TextBox...
    if (control is TextBox)
    {
        TextBox t = (TextBox)control;
        t.Enabled = false;
    }
  //遍历所有DateTimePicker...
    if (control is DateTimePicker)
    {
        DateTimePicker d = (DateTimePicker)control;
        d.Enabled = false;
    }
}

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

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

结果:

结果显示所有控件都被获取到了。

猜你喜欢

转载自blog.csdn.net/u014453443/article/details/85088733
今日推荐