Thomas Rollet
Thomas Rollet

Reputation: 1569

Put Bold font in title of tab in a tabcontrol c#

I've got this tab control:

tabcontrol2

I need to put the tab name "Notes" in a bold font but I don't know how to.

I tried this code:

tabControl2.Font = new Font(this.Font, FontStyle.Bold);

However, it put all tabs in bold. Then I tried this:

tabControl2.TabPages["Notes"].Font = new Font(this.Font, FontStyle.Bold);

I also tried this : How do I make a TabPage's title text bold?

Graphics g = e.Graphics;
            Brush _TextBrush;

            // Get the item from the collection.
            TabPage _TabPage = tabControl2.TabPages["Notes"];

            // Get the real bounds for the tab rectangle.
            Rectangle _TabBounds = tabControl2.GetTabRect(1);

            _TextBrush = new System.Drawing.SolidBrush(e.ForeColor);

            // Use our own font. Because we CAN.
            Font _TabFont = new Font(e.Font.FontFamily, (float)9, FontStyle.Bold, GraphicsUnit.Pixel);

            // Draw string. Center the text.
            StringFormat _StringFlags = new StringFormat();
            _StringFlags.Alignment = StringAlignment.Center;
            _StringFlags.LineAlignment = StringAlignment.Center;
            g.DrawString(tabControl2.TabPages["Notes"].Text, _TabFont, _TextBrush, _TabBounds, new StringFormat(_StringFlags));

However, it put all the content of the tab in bold and not the title. I don't know how to put the title of this specific tabpage. Does anyone have an idea ?

Upvotes: 4

Views: 3355

Answers (1)

simo
simo

Reputation: 44

I hope I can be of any help to you. 

enter image description here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        tabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
        tabControl.DrawItem += TabControlOnDrawItem;
    }

    private FontStyle HasNotification(string tabText)
    {
        return tabText.Equals("Notes") && true 
                   ? FontStyle.Bold
                   : FontStyle.Regular;
    }

    private void TabControlOnDrawItem(object sender, DrawItemEventArgs e)
    {
        var tab = (TabControl) sender;

        var tabText = tab.TabPages[e.Index].Text;

        e.Graphics
         .DrawString(tabText
                     , new Font(tab.Font.FontFamily
                                , tab.Font.Size
                                , HasNotification(tabText))
                     , Brushes.Black
                     , e.Bounds
                     , new StringFormat
                       {
                           Alignment = StringAlignment.Center,
                           LineAlignment = StringAlignment.Center
                       });
    }
}

Upvotes: 1

Related Questions