将表单作为选项卡






4.60/5 (3投票s)
在 C#.Net 中轻松打开表单作为选项卡
引言
我在 .NET 中做过一些项目,这是我的第一篇文章。
我搜索过将 WinForms 作为选项卡使用的解决方案,但这些解决方案过于高级。我的风格是找到解决方案,尝试理解代码,然后写我自己的,这样我才能更好地理解并记住,以便下次使用。但不幸的是,我找到的解决方案过于高级,我无法理解代码。
背景
今天,我正在尝试找到如何将一个 WinForm 添加到另一个 WinForm 作为
private void btnOpneForm_Click(object sender, EventArgs e)
{
Form childForm = new Form();
childForm.Parent = this;
childForm.WindowState = FormWindowState.Maximized;
childForm.Show();
}
运行这段代码会报错“无法将顶级控件添加到控件中”。我搜索并找到了解决方案;很简单。我所要做的就是将 childForm
的 TopLevel
属性设置为 false。然后它就起作用了!现在,这给了我一个想法 ('',)...
Using the Code
我将 tabControl1
添加到父表单,创建了一个新的 TabPage
,并将此表单添加到 TabPage
中。
代码如下
//
// stophereareyou@gmail.com
//
Form childForm = new Form();
public Form2()
{
InitializeComponent();
childForm.FormClosing += new FormClosingEventHandler(childForm_FormClosing);
}
void childForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Close Parent Tab
childForm.Parent.Dispose();
}
private void btnOpneForm_Click(object sender, EventArgs e)
{
//TopLevel for form is set to false
childForm.TopLevel = false;
//Added new TabPage
TabPage tbp =new TabPage();
tabControl1.TabPages.Add(tbp);
tbp.Controls.Add(childForm);
//Added form to tabpage
childForm.WindowState = FormWindowState.Maximized;
childForm.Show();
}
点击按钮 btnOpneForm
会在 TabPage tbp
中打开 childForm
。