C# WinForm遍歷窗體控件的3種方法
1.循環(huán)遍歷
private void GetControls(Control fatherControl)
{
Control.ControlCollection sonControls = fatherControl.Controls;
foreach (Control control in sonControls)
{
listBox1.Items.Add(control.Name);
}
}
結(jié)果:能獲取到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);
}
}
}
結(jié)果:能獲取到絕大多數(shù)控件
問題: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);
}
}
結(jié)果:所有控件都被獲取到了
DevExpress控件無法使用this.Controls進(jìn)行遍歷,只能通過反射的方法獲得,如下代碼:
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種方法的詳細(xì)內(nèi)容,更多關(guān)于WinForm遍歷窗體控件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C# Winform 實(shí)現(xiàn)控件自適應(yīng)父容器大小的示例代碼
- C# WinForm-Timer控件的使用
- c# Winform自定義控件-儀表盤功能
- C# winform自定義翻頁控件詳解
- C# WinForm實(shí)現(xiàn)窗體上控件自由拖動(dòng)功能示例
- C# WinForm制作異形窗體與控件的方法
- C#中WinForm控件的拖動(dòng)和縮放的實(shí)現(xiàn)代碼
- C# WinForm控件對(duì)透明圖片重疊時(shí)出現(xiàn)圖片不透明的簡(jiǎn)單解決方法
- C# Winform 子窗體訪問父級(jí)窗體的控件和屬性
- c# Winform同一數(shù)據(jù)源多個(gè)控件保持同步
相關(guān)文章
C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標(biāo)
這篇文章主要介紹了C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標(biāo),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
C#使用IronPython庫調(diào)用Python腳本
這篇文章介紹了C#使用IronPython庫調(diào)用Python腳本的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
Unity UI實(shí)現(xiàn)拖拽旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Unity UI實(shí)現(xiàn)拖拽旋轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
10個(gè)C#程序員經(jīng)常用到的實(shí)用代碼片段
如果你是一個(gè)C#程序員,那么本文介紹的10個(gè)C#常用代碼片段一定會(huì)給你帶來幫助,從底層的資源操作,到上層的UI應(yīng)用,這些代碼也許能給你的開發(fā)節(jié)省不少時(shí)間。以下是原文:2015-09-09
WPF實(shí)現(xiàn)能自由改變形狀的四邊形和六邊形
這篇文章主要為大家詳細(xì)介紹了WPF如何實(shí)現(xiàn)能自由改變形狀的四邊形和六邊形,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-03-03

