using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace qqqqq
{
public partial class Form1 : Form
{
public Form1()
: base()
{
InitializeComponent();
}
private Icon icon = null;
int PageMaxIndex = 0;
private void button1_Click(object sender, System.EventArgs e)
{
PageMaxIndex++;
tabControl1.TabPages.Add(new TabPage("ABC-" + PageMaxIndex));
}
//关闭区域的宽高
const int CLOSE_SIZE = 15;
//重画
private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
Graphics g = e.Graphics;
using (Pen p = new Pen(this.ForeColor))
{
Rectangle myTabRect = tabControl1.GetTabRect(e.Index);
//把字写上
g.DrawString(tabControl1.TabPages[e.Index].Text
, this.Font
, SystemBrushes.ControlText
, myTabRect.X + 2, myTabRect.Y + 2);
//模拟绘制一个区域表示关闭的的地方(是一个红色的方块区域)
//当然大多时候画一个图就可以了 12*12的
myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
myTabRect.Width = CLOSE_SIZE;
myTabRect.Height = CLOSE_SIZE;
//g.DrawRectangle(p, myTabRect);
icon = qqqqq.Properties.Resources._2;
g.DrawIcon(icon, myTabRect);
}
}
private void tabControl1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x = e.X, y = e.Y;
//计算关闭区域
Rectangle myTabRect = tabControl1.GetTabRect(tabControl1.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)
{
tabControl1.TabPages.Remove(tabControl1.SelectedTab);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
//设置若干属性
tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
tabControl1.Padding = new System.Drawing.Point(15, 0);
tabControl1.DrawItem += new DrawItemEventHandler(tabControl1_DrawItem);
tabControl1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tabControl1_MouseDown);
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
}
}
上面是百度下就能出来的东西,接下来一些注意点
1.代码中出现了Resources._2,是这样添加进去的就是添加一个关闭的图片
2.操蛋的是,很多时候,代码一模一样都不能运行,这时候是因为Form1_Load是你手动输入的,你需要在vs设计界面双击生成,这样才能正常运行