您的位置:首页 > 其它

设计时获取窗体中所有组件名称

2013-03-24 11:00 141 查看
If you are hosting windows forms designer and using DesignerSurface, all components on the form that are visible in design time are accessible through DesignerSurface.ComponentsContainer property:

for (int i = 0; i < surface.ComponentContainer.Components.Count; i++)
{
Console.WriteLine((i + 1) + ". " + surface.ComponentContainer.Components[i].Site.Name + ": " +       surface.ComponentContainer.Components[i].GetType().FullName);
}


host.CreateComponent(typeof(Form));
Form frm1 = (Form)Activator.CreateInstance(frmType);
Form frm2 = (Form)host.RootComponent;

//FieldInfo fi = frmType.GetField("components", BindingFlags.Instance | BindingFlags.NonPublic);
//Container cn = null;
//if (fi != null)
//  cn = (Container)fi.GetValue(frm1);

//if (cn != null)
//  foreach (Component cp in cn.Components)
//  {
//    host.Container.Add(cp);
//    ComponentDesigner componentDesigner1 = ((ComponentDesigner)host.GetDesigner(((IComponent)cp)));
//    if (componentDesigner1 != null)
//      componentDesigner1.InitializeExistingComponent(((IDictionary)null));

//  }

FieldInfo[] fis = frmType.GetFields( BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo f in fis)
{
object o = f.GetValue(frm1);
if (o is Control)
continue;
if (o is Component)
{
Component cp = (Component)o;
host.Container.Add(cp);
ComponentDesigner componentDesigner1 = ((ComponentDesigner)host.GetDesigner(((IComponent)cp)));
if (componentDesigner1 != null)
componentDesigner1.InitializeExistingComponent(((IDictionary)null));
}
}


private void button1_Click(object sender, EventArgs e)
{
Type t = typeof(Form1);
object frm = Activator.CreateInstance(t);
FieldInfo field = t.GetField("components", BindingFlags.Instance | BindingFlags.NonPublic);
if (field != null)
{
IContainer componentsContainer = field.GetValue(frm) as IContainer;
if (componentsContainer != null)
{
// access components ny name, by index, in a loop ...
for (int i = 0; i < componentsContainer.Components.Count; i++)
{
Console.WriteLine(i + ". component: " + componentsContainer.Components[i].GetType().FullName);
}

}
}
}


Regards,
vladimir
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: