您的位置:首页 > 编程语言 > C#

C#在Tabcontrol选项卡上加图片,点击图片关闭选项卡

2011-08-29 16:56 447 查看
实现的功能:重写TabControl控件。要先在项目中加入图片close,新建的选项卡就带上了关闭的图标。
using System;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

using System.Drawing;

namespace MengYe.writeclass

{



/// <summary>

/// 重写的TabControl控件

/// </summary>

public class SimpleTabControl : TabControl

{

private int iconWidth = 15;

private int iconHeight = 13;

private Image icon = null;

private Brush biaocolor = Brushes.White; //选项卡的背景色

public SimpleTabControl(): base()

{

this.ItemSize = new Size(50, 28); //设置选项卡标签的大小,可改变高,不可改变宽



this.Appearance = TabAppearance.Buttons; //选项卡的显示模式

this.DrawMode = TabDrawMode.OwnerDrawFixed;

icon = MengYe.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(biaocolor, r); //改变选项卡标签的背景色

string title = this.TabPages[e.Index].Text;

g.DrawString(title, this.Font, new SolidBrush(Color.Black), new PointF(r.X + 3, r.Y +6));//PointF选项卡标题的位置

r.Offset(r.Width - iconWidth - 3, 2);

g.DrawImage(icon, new Point(r.X-2, r.Y+2));//选项卡上的图标的位置

}

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)) //点击特定区域时才发生

{

//关闭选项卡中加载的窗口

foreach (Form cform in Application.OpenForms)

{

if (cform.Name == this.SelectedTab.Name)

{

cform.Close();

break;

}

}

this.TabPages.Remove(this.SelectedTab);

}

}

/// <summary>

/// 选择选项卡时发生的事件

/// </summary>

/// <param name="e"></param>

protected override void OnSelecting(TabControlCancelEventArgs e)

{

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: