无需派生类,这里有一个简洁的片段:http://www.dotnetthoughts.net/implementing-close-button-in-tab-pages/ http://www.dotnetthoughts.net/implementing-close-button-in-tab-pages/
将选项卡控件的 DrawMode 属性设置为 OwnerDrawFixed。该属性决定系统或开发人员是否可以绘制标题。
在选项卡控件的 DrawItem 事件中添加代码 - 将调用该事件来绘制每个选项卡页。
//This code will render a "x" mark at the end of the Tab caption.
e.Graphics.DrawString("x", e.Font, Brushes.Black, e.Bounds.Right - 15, e.Bounds.Top + 4);
e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top + 4);
e.DrawFocusRectangle();
现在,对于关闭按钮操作,我们需要将以下代码添加到选项卡控件的 MouseDown 事件中。
//Looping through the controls.
for (int i = 0; i < this.tabControl1.TabPages.Count; i++)
{
Rectangle r = tabControl1.GetTabRect(i);
//Getting the position of the "x" mark.
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 9, 7);
if (closeButton.Contains(e.Location))
{
if (MessageBox.Show("Would you like to Close this Tab?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.tabControl1.TabPages.RemoveAt(i);
break;
}
}
}