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);
}
}
}
}
以上就是C# WinForm遍历窗体控件的3种方法的详细内容,更多关于WinForm遍历窗体控件的资料请关注编程网其它相关文章!