且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WinForms TabControl - 添加新标签按钮 (+)

更新时间:2022-10-15 11:03:13

You can add a new tab to the end of tabs of control and set it's text to + and then:

  • Check if the user clicked on the last tab, then insert a new tab before it.
  • You should prevent selection of the last tab.
  • You should adjust the width of tabs and let the last tab have smaller width.

Then you will have a tab control like below. To have larger tab buttons, I have applied a padding to the control.

Hanlde Click on Last Tab

You can handle MouseDown or MouseClick event and check if the last tab rectangle contains the mouse clicked point, then insert a tab before the last tab:

private void tabControl1_MouseDown(object sender, MouseEventArgs e)
{
    var lastIndex = this.tabControl1.TabCount - 1;
    if (this.tabControl1.GetTabRect(lastIndex).Contains(e.Location))
    {
        this.tabControl1.TabPages.Insert(lastIndex, "New Tab");
        this.tabControl1.SelectedIndex = lastIndex;
    }
}

Prevent Selectin of Last Tab

To prevent selection of last tab, you can handle Selecting event of control and check if the selecting tab is the last tab, cancel the event:

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPageIndex == this.tabControl1.TabCount - 1)
        e.Cancel = true;
}

Adjust Width of Tabs

To adjust tab width and let the last tab have smaller width, you can hanlde HandleCreated event and send a TCM_SETMINTABWIDTH to the control and specify the minimum size allowed for the tab width:

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int TCM_SETMINTABWIDTH = 0x1300 + 49;
private void tabControl1_HandleCreated(object sender, EventArgs e)
{
    SendMessage(this.tabControl1.Handle, TCM_SETMINTABWIDTH, IntPtr.Zero, (IntPtr)16);
}

Note

  • You can simply encapsulate the logic in a derived TabContol and make a custom tab control which supports adding tabs.

  • Close button: Also you can simply make the control owner-draw and handle Painting of tabs to show a + icon and X icon on tabs. As an example you can see an implementation in this post: TabControl with Close and Add Button.

  • Right to Left (RTL) support: You can add support for RTL when using owner-draw tab. This post: Close button for TabPages of Right To Left TabControl is a solution.