修改此代码(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标签标题中添加关闭按钮
时间: 2024-02-14 20:12:32 浏览: 190
给TabHeader控件添加关闭标签并编辑该控件
4星 · 用户满意度95%
以下是修改后的代码,它会在每个标签的标题中添加一个关闭按钮,并在单击该按钮时关闭相关的选项卡和窗体:
```
private void AddCloseButtonToTabPage(TabPage tabPage)
{
// 创建一个关闭按钮
Button closeButton = new Button();
closeButton.Text = "×";
closeButton.Size = new Size(16, 16);
closeButton.FlatStyle = FlatStyle.Flat;
closeButton.BackColor = Color.Transparent;
closeButton.ForeColor = Color.Red;
closeButton.FlatAppearance.BorderSize = 0;
closeButton.TabStop = false;
// 设置关闭按钮的位置和大小
Rectangle rect = tabPage.GetTabRect(tabPage.Controls.Count - 1);
closeButton.Location = new Point(rect.Right - closeButton.Width, rect.Top + (rect.Height - closeButton.Height) / 2);
// 将关闭按钮添加到标签页中
tabPage.Controls.Add(closeButton);
// 为关闭按钮绑定事件
closeButton.Click += (sender, e) =>
{
TabPage tabPage = (sender as Button).Parent as TabPage;
Form form = tabPage.Tag as Form;
form.Close();
tabControl1.TabPages.Remove(tabPage);
};
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
// 添加关闭按钮到当前选中的标签页
TabPage tabPage = tabControl1.SelectedTab;
AddCloseButtonToTabPage(tabPage);
}
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
// 添加关闭按钮到新添加的标签页
TabPage tabPage = e.Control as TabPage;
AddCloseButtonToTabPage(tabPage);
}
```
阅读全文