自定義控件代碼如下:
using System.Drawing;
using System.Windows.Forms;
namespace Demo.UC
{
public class KKTab : TabControl
{
private int IconWOrH = 16;
private Image icon = null;
public KKTab()
: base()
{
this.DrawMode = TabDrawMode.OwnerDrawFixed;
icon = Demo.Properties.Resources.close;
IconWOrH = icon.Width;
IconWOrH = icon.Height;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Rectangle r = GetTabRect(e.Index);
if (e.Index == this.SelectedIndex) //當前選中的Tab頁,設置不同的樣式以示選中
{
Brush selected_color = Brushes.SteelBlue; //選中的項的背景色
g.FillRectangle(selected_color, r); //改變選項卡標簽的背景色
string title = this.TabPages[e.Index].Text;
g.DrawString(title, this.Font, new SolidBrush(Color.Black), new PointF(r.X , r.Y + 5));//PointF選項卡標題的位置
r.Offset(r.Width - IconWOrH, 2);
g.DrawImage(icon, new Point(r.X, r.Y));//選項卡上的圖標的位置 fntTab = new System.Drawing.Font(e.Font, FontStyle.Bold);
}
else//非選中的
{
Brush selected_color = Brushes.AliceBlue; //選中的項的背景色
g.FillRectangle(selected_color, r); //改變選項卡標簽的背景色
string title = this.TabPages[e.Index].Text+" ";
g.DrawString(title, this.Font, new SolidBrush(Color.Black), new PointF(r.X , r.Y + 5));//PointF選項卡標題的位置
r.Offset(r.Width - IconWOrH, 2);
g.DrawImage(icon, new Point(r.X, r.Y));//選項卡上的圖標的位置
}
}
protected override void OnMouseClick(MouseEventArgs e)
{
Point point = e.Location;
Rectangle r = GetTabRect(this.SelectedIndex);
r.Offset(r.Width - IconWOrH - 3, 2);
r.Width = IconWOrH;
r.Height = IconWOrH;
if (r.Contains(point)) this.TabPages.RemoveAt(this.SelectedIndex);
}
}
}
注意:使用方式:界面加載需處理TabPage Text屬性
foreach (TabPage item in this.kkTab1.TabPages)
{
item.Text = item.Text + " ";
}
運行效果如下:

