C# 用窗体的名字Name打开窗体
新建2个窗体Form1,Form2
Form1中创建1个按钮,按钮的text填入Form2
双击按钮写入
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void CreateForm(string strName, string AssemblyName)
{
string path = AssemblyName;//项目的Assembly选项名称
string name = strName; //类的名字
Form doc = (Form)Assembly.Load(path).CreateInstance(name);//窗体实例化
if (doc != null)//判断是否实例化成功
doc.Show();//打开窗体
else
MessageBox.Show("要打开的"+name+"窗体不存在");
}
private void button1_Click(object sender, EventArgs e)
{
string btnname = ((Button)sender).Text;//获取按钮text
string fullstr = Assembly.GetExecutingAssembly().FullName;//获取项目信息
fullstr = fullstr.Substring(0, fullstr.IndexOf(","));//截取项目名称
CreateForm(fullstr+"." + btnname,fullstr);
}
}
}