选项卡带关闭按钮的TabControl
很多软件,像FireFox之类的多页面组织的软件,都在选项卡标签的右边放一按钮,以方便用户关闭选项卡。然而dotnet自带的TabControl并没有这个功能。不过。它提供了OnDrawItem方法供用户重载。在这个方法里面我们可以自己画标签。综合两个别人写的代码。我写了个自定义的TabControl控件。代码如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
namespace SimplePlayerApp.Controls
{
public class SimpleTabControl:TabControl
{
private int iconWidth = 15;
private int iconHeight = 13;
private Image icon = null;
public SimpleTabControl():base()
{
this.DrawMode = TabDrawMode.OwnerDrawFixed;
icon = SimplePlayerApp.Properties.Resources.close;
iconWidth = icon.Width;
iconHeight = icon.Height;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Rectangle r = GetTabRect(e.Index);
g.FillRectangle(Brushes.White, r);
string title = this.TabPages[e.Index].Text;
g.DrawString(title, this.Font, new SolidBrush(Color.Black), new PointF(r.X + 2, r.Y + 2));
r.Offset(r.Width - iconWidth - 3, 2);
g.DrawImage(icon, new Point(r.X, r.Y));
}
protected override void OnMouseClick(MouseEventArgs e)
{
Point p = e.Location;
Rectangle r = GetTabRect(this.SelectedIndex);
r.Offset(r.Width - iconWidth - 3, 2);
r.Width = iconWidth;
r.Height = iconHeight;
if (r.Contains(p)) this.TabPages.RemoveAt(this.SelectedIndex);
}
}
}
这个过程中,我优化了一些冗余代码,这个样子就相当优美了。在这儿,我们还可写一些属性,用于控制标签的字体色、背影色、字体等等。可惜,TabControl好像不支持设置标签的宽度、高度、文本对齐的方式。上面代码只是完成最困难的部分。其余功能要加上就很容易了。代码也就不再贴了。
参考资料:
CodeProject:A TabControl With tab Page Closing Capability
求带关闭按钮的TabControl控件
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
namespace SimplePlayerApp.Controls
{
public class SimpleTabControl:TabControl
{
private int iconWidth = 15;
private int iconHeight = 13;
private Image icon = null;
public SimpleTabControl():base()
{
this.DrawMode = TabDrawMode.OwnerDrawFixed;
icon = SimplePlayerApp.Properties.Resources.close;
iconWidth = icon.Width;
iconHeight = icon.Height;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Rectangle r = GetTabRect(e.Index);
g.FillRectangle(Brushes.White, r);
string title = this.TabPages[e.Index].Text;
g.DrawString(title, this.Font, new SolidBrush(Color.Black), new PointF(r.X + 2, r.Y + 2));
r.Offset(r.Width - iconWidth - 3, 2);
g.DrawImage(icon, new Point(r.X, r.Y));
}
protected override void OnMouseClick(MouseEventArgs e)
{
Point p = e.Location;
Rectangle r = GetTabRect(this.SelectedIndex);
r.Offset(r.Width - iconWidth - 3, 2);
r.Width = iconWidth;
r.Height = iconHeight;
if (r.Contains(p)) this.TabPages.RemoveAt(this.SelectedIndex);
}
}
}
这个过程中,我优化了一些冗余代码,这个样子就相当优美了。在这儿,我们还可写一些属性,用于控制标签的字体色、背影色、字体等等。可惜,TabControl好像不支持设置标签的宽度、高度、文本对齐的方式。上面代码只是完成最困难的部分。其余功能要加上就很容易了。代码也就不再贴了。
参考资料:
CodeProject:A TabControl With tab Page Closing Capability
求带关闭按钮的TabControl控件