这篇文章主要介绍了C# WinForm遍历窗体控件的3种方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下
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遍历窗体控件的资料请关注得得之家其它相关文章!
织梦狗教程
本文标题为:C# WinForm遍历窗体控件的3种方法


基础教程推荐
猜你喜欢
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08
- C#中 Json 序列化去掉null值的方法 2022-11-18
- Unity shader实现高斯模糊效果 2023-01-16
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C# 解析XML和反序列化的示例 2023-04-14