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

 

本文链接:https://blog.csdn.net/u014453443/article/details/85088733

扣扣技术交流群:460189483

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

  1.  
    //遍历窗体所有控件,
  2.  
    foreach (Control control in this.Controls)
  3.  
    {
  4.  
    //遍历后的操作...
  5.  
    control.Enabled = false;
  6.  
    }
  1.  
    遍历某个panel的所有控件
  2.  
     
  3.  
    foreach (Control control in this.panel4.Controls)
  4.  
    {
  5.  
    control.Enabled = false;
  6.  
    }
  1.  
    遍历所有TextBox类型控件或者所有DateTimePicker控件
  2.  
     
  3.  
    复制代码
  4.  
    foreach (Control control in this.Controls)
  5.  
    {
  6.  
      //遍历所有TextBox...
  7.  
    if (control is TextBox)
  8.  
    {
  9.  
    TextBox t = (TextBox)control;
  10.  
    t.Enabled = false;
  11.  
    }
  12.  
      //遍历所有DateTimePicker...
  13.  
    if (control is DateTimePicker)
  14.  
    {
  15.  
    DateTimePicker d = (DateTimePicker)control;
  16.  
    d.Enabled = false;
  17.  
    }
  18.  
    }

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

1. 最简单的方式:

  1.  
    private void GetControls1(Control fatherControl)
  2.  
    {
  3.  
    Control.ControlCollection sonControls = fatherControl.Controls;
  4.  
    //遍历所有控件
  5.  
    foreach (Control control in sonControls)
  6.  
    {
  7.  
    listBox1.Items.Add(control.Name);
  8.  
    }
  9.  
    }

 结果:

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

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

  1.  
    private void GetControls1(Control fatherControl)
  2.  
    {
  3.  
    Control.ControlCollection sonControls = fatherControl.Controls;
  4.  
    //遍历所有控件
  5.  
    foreach (Control control in sonControls)
  6.  
    {
  7.  
    listBox1.Items.Add(control.Name);
  8.  
    if (control.Controls != null)
  9.  
    {
  10.  
    GetControls1(control);
  11.  
    }
  12.  
    }
  13.  
    }

结果:

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

3. 使用反射(Reflection)

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

结果:

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

 
原文地址:https://www.cnblogs.com/wfy680/p/12002269.html