Windows Forms: Add close button to tab control in C#

This post shows you How to Add close button to TabControl TabPages in C# .NET Windows Forms Application.

By default, TabControl doesn't support the close button, to create TabControl with the close button, you can modify your code as shown below.

Creating a new Windows Forms Application project, then open your form designer.

How to Add a close button to Tabs in TabControl c#

Dragging TabControl from your Visual Studio Toolbox to your form designer.

add close button to tab control c#

Right-clicking on the TabControl, then select Properties. Next, you need to set the DrawMode of your TabControl to OwnerDrawFixed.

Opening your code behind, then declare as shown below.

Point _imageLocation = new Point(20, 4);
Point _imgHitArea = new Point(20, 4);
Image closeImage;

Right-clicking on your project, then select Properties => Resources. Next, Copy a close button image (16x16) into the Resources tab.

add resource into project in visual studio

Adding a Form_Load event handler to your form allows you to initialize a close button with TabControl.

private void Form1_Load(object sender, EventArgs e)
{
    closeImage = Properties.Resources.close;
    tabControl1.Padding = new Point(20, 4);
}

Adding a Draw_Item event handler to the TabControl allows you to draw image close button to the TabPages.

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    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));
    e.Graphics.DrawImage(img, new Point(r.X + (this.tabControl1.GetTabRect(e.Index).Width - _imageLocation.X), _imageLocation.Y));
}

Adding a Mouse_Click event handler to the TabControl allows you to remove TabPage.

private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
    TabControl tabControl = (TabControl)sender;
    Point p = e.Location;
    int _tabWidth = 0;
    _tabWidth = this.tabControl1.GetTabRect(tabControl.SelectedIndex).Width - (_imgHitArea.X);
    Rectangle r = this.tabControl1.GetTabRect(tabControl.SelectedIndex);
    r.Offset(_tabWidth, _imgHitArea.Y);
    r.Width = 16;
    r.Height = 16;
    if (tabControl1.SelectedIndex >= 1)
    {
        if (r.Contains(p))
        {
            TabPage tabPage = (TabPage)tabControl.TabPages[tabControl.SelectedIndex];
            tabControl.TabPages.Remove(tabPage);
        }
    }
}

Through this c# example, i hope so you can easily create c# close tabs for TabControl.

Related