Add close button to TabControl TabPages in C#
In this tutorial we will see how to enable user to close a TabPage by adding a close button to the Tab header like this:
First we add some variables:
closeR is a close button png image in resources folder of the project.
Then we re-write Draw_Item method of TabControl:
In Mouse_Click event of the TabControl:
More explanation in this video:
First we add some variables:
public partial class Form1 : Form
{
private Point _imageLocation = new Point(13, 5);
private Point _imgHitArea = new Point(13, 2);
Image CloseImage;
public Form1()
{
InitializeComponent();
}
}
In Form_Load event we add this code:tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
tabControl1.DrawItem += tabControl1_DrawItem;
CloseImage = WindowsFormsApplication3.Properties.Resources.closeR;
tabControl1.Padding = new Point(10, 3);
Then we re-write Draw_Item method of TabControl:
private void TabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
try
{
Image img = new Bitmap(CloseImage);
Rectangle r = e.Bounds;
r = this.tabControl1.GetTabRect(e.Index);
r.Offset(2, 2);
Brush TitleBrush = new SolidBrush(Color.Black);
Font f = this.Font;
string title = this.tabControl1.TabPages[e.Index].Text;
e.Graphics.DrawString(title, f, TitleBrush, new PointF(r.X, r.Y));
if (tabControl1.SelectedIndex >= 1)
{
e.Graphics.DrawImage(img, new Point(r.X + (this.tabControl1.GetTabRect(e.Index).Width - _imageLocation.X), _imageLocation.Y));
}
}
catch (Exception) { }
}
In Mouse_Click event of the TabControl:
TabControl tc = (TabControl)sender;
Point p = e.Location;
int _tabWidth = 0;
_tabWidth = this.tabControl1.GetTabRect(tc.SelectedIndex).Width - (_imgHitArea.X);
Rectangle r = this.tabControl1.GetTabRect(tc.SelectedIndex);
r.Offset(_tabWidth, _imgHitArea.Y);
r.Width = 16;
r.Height = 16;
if (tabControl1.SelectedIndex >= 1)
{
if (r.Contains(p))
{
TabPage TabP = (TabPage)tc.TabPages[tc.SelectedIndex];
tc.TabPages.Remove(TabP);
}
}
More explanation in this video:
Add close button to TabControl TabPages in C#
Reviewed by Bloggeur DZ
on
00:01
Rating:
how can i open this form in tabpages please tell me
RépondreSupprimer1. If I want that when the mouse is positioned on top of the image, it changes to another as it would be done?
RépondreSupprimer2. if I wanted the image of x not to appear in all the tabpages as I would do?
thanks
I am unable to see that close png, I took and image of 16 X 16 . could you please help me out ?
RépondreSupprimer