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遍歷窗體控件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Unity3D Shader實(shí)現(xiàn)掃描顯示效果
這篇文章主要為大家詳細(xì)介紹了Unity3D Shader實(shí)現(xiàn)掃描顯示效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-03-03
C# WinForm創(chuàng)建Excel文件的實(shí)例
下面小編就為大家?guī)硪黄狢# WinForm創(chuàng)建Excel文件的實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
VS2010寫的程序在自己電腦可以運(yùn)行、其他電腦上不能運(yùn)行的解決方案
自己用Visual Studio 2010 旗艦版寫了一個軟件,在自己電腦上運(yùn)行完全沒有問題,但是拷貝到其他人電腦上之后不管雙擊還是以管理身份運(yùn)行,均沒有反應(yīng),進(jìn)程管理器中相關(guān)進(jìn)程也只是一閃而過2013-04-04
C#實(shí)現(xiàn)在啟動目錄創(chuàng)建快捷方式的方法
這篇文章主要介紹了C#實(shí)現(xiàn)在啟動目錄創(chuàng)建快捷方式的方法,涉及C#快捷方式的創(chuàng)建技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09
使用Deflate算法對文件進(jìn)行壓縮與解壓縮的方法詳解
本篇文章是對使用Deflate算法對文件進(jìn)行壓縮和解壓縮的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
C#使用Post調(diào)用接口并傳遞json參數(shù)
這篇文章主要介紹了C#使用Post調(diào)用接口并傳遞json參數(shù),具有很好的參考價值,希望對大家有所幫助。2022-06-06

