C#反射动态调用窗体,动态实例化窗体的方法

其实这个问题很简单只要我们使用一点点反射的原理就行了,

C#反射动态调用窗体,动态实例化窗体的方法_第1张图片

单击那个按钮就会出现那个窗体,
如果非常多的按钮的话我们是不是一般会这样写

public static void CreateForm(string strName, string AssemblyName)

     {  

string path = AssemblyName;//项目的Assembly选项名称  

  string name = strName; //类的名字 

   Form doc = (Form)Assembly.Load(path).CreateInstance(name);

doc.Show();

       }
 
       private void button1_Click( object sender, EventArgs e)
       {
           //获取单击的Button名称
           string btnname = ((Button)sender).Text;
           CreateForm( "WindowsFormsApplication1." + btnname, "WindowsFormsApplication1" );
       }
UCBasicInfo.dll|UCBasicInfo.ucUpdate
  /// 打开窗体
        public void openClientForm(string windowName, string dllName, string className)
        {
            try
            {
                System.Type type = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + dllName).GetType(className, false);
                if (type == null)
                {
                    throw new Exception("未能加载菜单项" + windowName + ",请联系系统管理员!");
                }
                ucClientBase ucClient = (ucClientBase)Activator.CreateInstance(type);
                if (ucClient == null)
                {
                    return;
                }

                ucClient.client = this;
                ucClient.Name = windowName;
                ucClient.Dock = DockStyle.Fill;

                TabPage pg = new TabPage();
                pg.Tag = tcMain.SelectedTab;//记住之前打开的窗体,当改窗体关闭的时候跳到前一个窗体
                pg.Text = windowName;

                pg.Controls.Add(ucClient);
              
                if (!tabControlCheckHave(tcMain, pg.Text))
                {
                    tcMain.TabPages.Add(pg);
                    tcMain.SelectedTab = pg;
                }
                else
                {
                    pg.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


你可能感兴趣的:(C#,C#)