private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Level == 1) { // 获取选中的子级功能名称 string childNodeText = e.Node.Text; // 根据子级功能名称从字典中获取对应的From窗体类型 if (formTypes.TryGetValue(childNodeText, out Type formType)) { // 创建新的From窗体实例并添加到stabControl1中 Form form = (Form)Activator.CreateInstance(formType); form.TopLevel = false; form.FormBorderStyle = FormBorderStyle.None; form.Dock = DockStyle.Fill; TabPage tabPage = new TabPage(childNodeText); tabPage.Tag = form; tabPage.Controls.Add(form); tabPage.Controls.Add(new Button() { Text = "X", Dock = DockStyle.Right, Width = 30, Tag = tabPage, }); tabPage.Controls[1].Click += TabPage_CloseButtonClick; stabControl1.TabPages.Add(tabPage); stabControl1.SelectedTab = tabPage; form.Show(); } } } private void TabPage_CloseButtonClick(object sender, EventArgs e) { Button closeButton = (Button)sender; TabPage tabPage = (TabPage)closeButton.Tag; Form form = (Form)tabPage.Tag; form.Close(); stabControl1.TabPages.Remove(tabPage); }修改此代码为TabPages标题栏右边添加关闭(X)功能
时间: 2024-02-10 08:12:30 浏览: 127
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Level == 1)
{
// 获取选中的子级功能名称
string childNodeText = e.Node.Text;
// 根据子级功能名称从字典中获取对应的From窗体类型
if (formTypes.TryGetValue(childNodeText, out Type formType))
{
// 创建新的From窗体实例并添加到stabControl1中
Form form = (Form)Activator.CreateInstance(formType);
form.TopLevel = false;
form.FormBorderStyle = FormBorderStyle.None;
form.Dock = DockStyle.Fill;
TabPage tabPage = new TabPage(childNodeText);
tabPage.Tag = form;
tabPage.Controls.Add(form);
Button closeButton = new Button()
{
Text = "X",
Dock = DockStyle.Right,
Width = 30,
Tag = tabPage
};
closeButton.Click += TabPage_CloseButtonClick;
tabPage.Controls.Add(closeButton);
stabControl1.TabPages.Add(tabPage);
stabControl1.SelectedTab = tabPage;
form.Show();
}
}
}
private void TabPage_CloseButtonClick(object sender, EventArgs e)
{
Button closeButton = (Button)sender;
TabPage tabPage = (TabPage)closeButton.Tag;
Form form = (Form)tabPage.Tag;
form.Close();
stabControl1.TabPages.Remove(tabPage);
}
以上是修改后的代码,将关闭按钮添加到了TabPage的右侧。当点击关闭按钮时,会触发TabPage_CloseButtonClick事件,这个事件会先关闭Form窗体,然后再将TabPage从stabControl1中移除。
阅读全文