默认情况下TabControl是无法通过界面关闭TabPage的
有些情况下我们需要手动关闭任意一个TabPage,如下图所示
TabControl控件自带属性是无法满足以上需求,下面简单介绍实现过程
1、首先需要对TabPage进行重绘,其目的是为了在TabPage上画出来一个"❌"符号。
(1)重绘前需要将TabControl的 DrawMode属性设置为OwnerDrawFixed。否则DrawDown事件不起作用
(2)在窗体Load事件中设置TabControl的Padding属性(增加TabPage的显示宽度,为"❌"符号让出位置): tabc.Padding = new Point(10, 0);
//tabc是TabControl的Name
private void tabc_DrawItem(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Rectangle rect = tabc.GetTabRect(e.Index);
TabPage page = tabc.TabPages[e.Index];
SolidBrush brushBack;
SolidBrush brushFront;
string text = page.Text;
//TabPage被选中时显示不同的前景色和背景色
if (tabc.SelectedTab == page)
{
brushBack = new SolidBrush(Color.Black);
brushFront = new SolidBrush(Color.White);
}
else
{
brushBack = new SolidBrush(Color.White);
brushFront = new SolidBrush(Color.Black);
}
g.FillRectangle(brushBack, rect);
Font font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
g.DrawString(text, new Font("宋体", 12f), brushFront, rect.X + 2, rect.Y + 5);
g.DrawString("×", font, brushFront, rect.Right - 22, rect.Bottom - 18);
}
2、对按钮添加关闭事件(删除TabPage事件)
private void tabc_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
TabPage page = tabc.SelectedTab;
Rectangle rect = tabc.GetTabRect(tabc.SelectedIndex);
Rectangle rect1 = new Rectangle(rect.Right - 22, rect.Y, 22, rect.Height);
int x = e.X;
int y = e.Y;
//判断鼠标位置是否位于“❌”的范围内
if (x > rect1.X && x < rect1.Right && y > rect1.Y && y < rect1.Bottom)
{
tabc.TabPages.Remove(page);
}
}
另附上通过代码对TabControl添加TabPage的实现过程
TabPage tabPage = new TabPage
{
Name = "name",
Text = "text"
};
tabc.TabPages.Add(tabPage);
tabc.SelectedTab = tabPage;