码迷,mamicode.com
首页 > 其他好文 > 详细

TabControl重写,添加关闭按钮

时间:2018-11-12 14:58:01      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:自己   dbr   bsp   bool   mbr   mouse   tom   wstring   mst   

 

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();

TabControl重写,添加关闭按钮

标签:自己   dbr   bsp   bool   mbr   mouse   tom   wstring   mst   

原文地址:https://www.cnblogs.com/masiteyi/p/9946094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!