.Net/Winform

C# TabControl Tab Background 변경

동구밖과수원 2012. 12. 11. 16:22

How to change the color of Tab Control (in c#)

Hi,
The Tab Control in .net does not expose properties to change its back ground and foreground color. This can be achieved by overriding the DrawItem event of the control. Following are the steps involved to do the same.
1. Set the TabControl's DrawMode to OwnerDraw
2. Handle the DrawItem event to draw things yourself
You may call the following method at the DrawItem event of tab control to test this.

        private void ChangeTabColor(DrawItemEventArgs e)
        {
            Font TabFont;
            Brush BackBrush = new SolidBrush(Color.Green); //Set background color
            Brush ForeBrush = new SolidBrush(Color.Yellow);//Set foreground color
            if (e.Index == this.tabControl1.SelectedIndex)
            {
                TabFont = new Font(e.Font, FontStyle.Italic FontStyle.Bold);
            }
            else
            {
                TabFont = e.Font;
            }
            string TabName = this.tabControl1.TabPages[e.Index].Text;
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            e.Graphics.FillRectangle(BackBrush, e.Bounds);
            Rectangle r = e.Bounds;
            r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
            e.Graphics.DrawString(TabName, TabFont, ForeBrush, r, sf);
            //Dispose objects
            sf.Dispose();
            if (e.Index == this.tabControl1.SelectedIndex)
            {
                TabFont.Dispose();
                BackBrush.Dispose();
            }
            else
            {
                BackBrush.Dispose();
                ForeBrush.Dispose();
            }
        }