先来看下效果
要实现这个功能,我们分两步来走,首先是需要绘制这个按钮,然后再对这个按钮的事件作出响应
1、将tabcontrol的绘制模式属性修改为OwnerDrawFixed,这样我们才能对DrawItem事件进行重写
DrawItem绘制标题前将我们需要的按钮绘制上去,代码如下
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();
2、注册一个tabcontrol鼠标的mousedown事件,然后在事件里面确定按钮坐标后作出响应,代码如下
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; } } }
来自一个整天想着回家卖牛肉的小码农