TabControl重写,添加关闭按钮
阅读原文时间:2023年09月24日阅读:1

class userTabControl : TabControl

{
const int CLOSE_SIZE = 15;
protected override void OnInvalidated(InvalidateEventArgs e)
{
this.DrawMode = TabDrawMode.OwnerDrawFixed;
this.Padding = new System.Drawing.Point(CLOSE_SIZE, 0);
base.OnInvalidated(e);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
try
{
Rectangle myTabRect = this.GetTabRect(e.Index);
//先添加TabPage属性
if (e.State == DrawItemState.Selected)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightYellow), myTabRect);
}
Brush br = e.State == DrawItemState.Selected ? Brushes.Red : SystemBrushes.ControlText;
e.Graphics.DrawString(this.TabPages[e.Index].Text, this.Font, br, myTabRect.X + 2, myTabRect.Y + 2);
//再画一个矩形框
using (Pen p = new Pen(Color.White))
{
myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 0);
myTabRect.Width = CLOSE_SIZE;
myTabRect.Height = CLOSE_SIZE;
e.Graphics.DrawRectangle(p, myTabRect);
}

//画关闭符号
Color clr = e.State == DrawItemState.Selected ? Color.Red : Color.Green;
using (Pen objpen = new Pen(clr, float.Parse("1.5")))
{
////=============================================
//自己画X
//"\"线
Point p1 = new Point(myTabRect.X + 3, myTabRect.Y + 3);
Point p2 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + myTabRect.Height - 3);
e.Graphics.DrawLine(objpen, p1, p2);
//"/"线
Point p3 = new Point(myTabRect.X + 3, myTabRect.Y + myTabRect.Height - 3);
Point p4 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + 3);
e.Graphics.DrawLine(objpen, p3, p4);

//e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, this.Font, objpen.Brush, p5);
}
e.Graphics.Dispose();
}
catch (Exception)
{ }

base.OnDrawItem(e);
}

protected override void OnDoubleClick(EventArgs e)
{
if (this.SelectedIndex >= 0)
{
this.TabPages.RemoveAt(this.SelectedIndex);
}
base.OnDoubleClick(e);
}

protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
try
{
int x = e.X, y = e.Y;
//计算关闭区域
Rectangle myTabRect = this.GetTabRect(this.SelectedIndex);

myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
myTabRect.Width = CLOSE_SIZE;
myTabRect.Height = CLOSE_SIZE;

//如果鼠标在区域内就关闭选项卡
bool isClose = x > myTabRect.X && x < myTabRect.Right && y > myTabRect.Y && y < myTabRect.Bottom;
if (isClose == true)
{
this.TabPages.Remove(this.SelectedTab);
}
}
catch
{
}
}
base.OnMouseDown(e);
}
}

使用方法:

1、添加userTabControl类。

2、添加TabControl控件,将Design文件中

this.tabControl1 = new System.Windows.Forms.TabControl(); 改为  this.tabControl1 = new userTabControl();

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章