C# 根据 一个画面的exe 解析出 里面所有的控件
我有一个 Winfrom 程序 有 From1 里面若干 控件!编译生成exe,
然后再建一个Winfrom 程序 读取 上一个 生成好的exe 将里面 用到的 所有的控件和其某些属性 列出显示!
(也可以只列出指定类型的控件 比如 TextBox Commbox Grid)
效果举例:
类型 名称 可见 可改
TextBox txt_Name true false
TextBox txt_Age true true
Commbox cbx_Country true true
... ... ... ...
看了下反射
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "|*.exe";
DialogResult dr = fd.ShowDialog();
if (dr == DialogResult.OK)
{
this.textBox1.Text = fd.FileName;
//加载exe
dllexe = Assembly.LoadFrom(fd.FileName);
//获取所有模块
Module[] modules = dllexe.GetModules();
//筛选Form模块
Type[] types = modules[0].GetTypes();
int i = 1;
foreach (Type t in types)
{
if (t.BaseType == typeof(Form))
{
PropertyInfo [] pis = t.GetProperties();
foreach (PropertyInfo pi in pis)
{
if (pi.PropertyType.Name == "ControlCollection")
{
//ControlCollection cc = pi.PropertyType;
}
}
}
}
到这里迷茫了,不知道怎么获取或转化 对象已获取 对象的属性!
求指点!
C# 反射?解析exe
[解决办法]
StringBuilder stringBuilder = new StringBuilder();
private void button1_Click(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type formType = assembly.GetType("WindowsFormsApplication1.Form1");
Object formObject = Activator.CreateInstance(formType);
BuildControlsTree(formType, formObject, 1);
MessageBox.Show(stringBuilder.ToString());
}
private void BuildControlsTree(Type type, Object obj, Int32 i)
{
var controlsProperty = type.GetProperty("Controls");
ICollection controls = controlsProperty.GetValue(obj) as ICollection;
if (controls == null
[解决办法]
controls.Count == 0)
{
return;
}
foreach (var item in controls)
{
Type controlType = item.GetType();
stringBuilder.AppendLine(new String(' ', i) + controlType.Name);
BuildControlsTree(controlType, item, (i + 1) * 3);
}
}
Type t =this.GetType();
FieldInfo txt = t.GetField("TextBox1", BindingFlags.NonPublic
[解决办法]
BindingFlags.Instance);
if (txt != null)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(txt.FieldType);
PropertyDescriptor myProperty = properties.Find("Text", false);
if (myProperty != null)
{
Object ctr = txt.GetValue(this);
Response.Write(myProperty.GetValue(ctr));
}
}
else {
Response.Write("没找到控件");
}