读书人

c# 遍历当前应用程序 的所有控件,下面

发布时间: 2012-01-16 23:36:51 作者: rapoo

c# 遍历当前应用程序 的所有控件,下面这个程序只遍历到当前窗体,要怎么遍历整个项目的呢??/
c# 遍历当前应用程序 的所有控件,下面这个程序只遍历到当前窗体,要怎么遍历整个项目的呢??/
private void ClearTextBox()
{
foreach (System.Windows.Forms.Control control in this.Controls)
{
if (control is TextBox)
{
TextBox tb = new TextBox();
tb = (TextBox)control;
tb.Text =string.Empty;
}

}
}

[解决办法]
如果是VB.NET话,或许简单点

首先,遍历,需要知道, 遍历的窗体

要知道,要遍历的窗体, 就绪要在启动窗体时,建立一个全局, 一开窗体列表

之久,就简单了
[解决办法]
遍历整个项目的控件


得通过反射


通过反射取出当前程序集所有的从UI集成出来的类


在每个类中遍历它的控件
[解决办法]
System.Reflection.Assembly.GetTypes

这样可以取出 当前程序集所有的类型 自己再试试吧
[解决办法]
Assembly a = Assembly.LoadFile(Application.ExecutablePath);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
MessageBox.Show(t.Name);
}
[解决办法]

C# code
private void button1_Click(object sender, EventArgs e)        {             Assembly a = Assembly.LoadFile(Application.ExecutablePath);            Type[] types = a.GetTypes();            foreach (Type t in types)            {                if (t.BaseType.Name == "Form")                {                    Form f = (Form)Activator.CreateInstance(t, true);                                           if (f != null)                    {                        foreach (Control c in f.Controls)                        {                            MessageBox.Show(c.Name);                        }                    }                }            }        }
[解决办法]

还要考虑
如果窗口是继承了多次From就不仅仅是判断BaseType属性了,有可能是BaseType.BaseType. ...
如果那个窗体没有无参数的构造函数,Activator.CreateInstance执行是个问题。
探讨
C# code
private void button1_Click(object sender, EventArgs e)
{
Assembly a = Assembly.LoadFile(Application.ExecutablePath);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (t.BaseType.Name == "Form")
{
Form f = (Form)Activator.CreateInstance(t, true); …

读书人网 >.NET Framework

热点推荐