项目文件组织:
主程序界面:
将tabControl1中的两个选项页的tag分别写上form2和form3的类名称。
被包含窗体Form2:
被包含窗体Form3:
运行结果:from2和form3两个窗体都集成到form1中的选项卡中显示:
Form1实现代码:
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.Windows.Forms;
namespace tabWindowTest
{
public
partial
class
Form1 : Form
{
public
int
[] s = {
0
,
0
};
//用来记录from是否打开过
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(object sender, EventArgs e)
{
//初始打开时就加载Form2
string formClass =
"tabWindowTest.Form2"
GenerateForm(formClass, tabControl1);
}
private
void
tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if
(s[tabControl1.SelectedIndex]==
0
)
//只生成一次
{
btnX_Click(sender, e);
}
}
/// <summary>
/// 通用按钮点击选项卡 在选项卡上显示对应的窗体
/// </summary>
private
void
btnX_Click(object sender, EventArgs e)
{
string path = AssemblyName;//项目的Assembly选项名
string formClass = "Form3";
GenerateForm(path +"."+formClass, sender);
}
//在选项卡中生成窗体
public
void
GenerateForm(string form, object sender)
{
string path = AssemblyName;//项目的Assembly选项名称
// 反射生成窗体
Form fm = (Form)Assembly.Load(path).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
;
}
}
}