知识要点:利用反射动态的加载窗体到对应的TabPage的。
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 MDITest { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } public int[] s = { 0, 0, 0 };//用来记录窗体是否打开过 private void MainForm_Load(object sender, EventArgs e) { //默认加载CNC窗体 string formClass = "MDITest.CNC"; GenerateForm(formClass, tabControl1); } public void GenerateForm(string form,object sender) { //反射生成窗体 Form fm = (Form)Assembly.GetExecutingAssembly().CreateInstance(form); //设置窗体没有边框,加入到选项卡中 fm.FormBorderStyle = FormBorderStyle.None; fm.TopLevel = false; fm.Parent = ((TabControl)sender).SelectedTab; fm.ControlBox = false; fm.Dock = DockStyle.Fill; fm.Show(); s[((TabControl)sender).SelectedIndex] = 1; } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { //只生成一次 if(s[tabControl1.SelectedIndex]==0) { btn_Click(sender,e); } } /// <summary> /// 通用按钮点击选项卡 在选项卡上显示对应的窗体 /// </summary> private void btn_Click(object sender,EventArgs e) { string formClass=((TabControl)sender).SelectedTab.Tag.ToString(); GenerateForm(formClass, sender); } } }