设置TabPage标头颜色

问题描述 投票:27回答:4

问候,

我有一个选项卡控件,我想在其中一个选项卡上更改事件的文本颜色。我找到了类似C# - TabPage Color event的答案和C# Winform: How to set the Base Color of a TabControl (not the tabpage)但是使用这些设置所有颜色,而不是所有颜色。

所以我希望有一种方法可以通过我希望将其更改为方法而不是事件的选项卡来实现此功能?

类似:

public void SetTabPageHeaderColor(TabPage page, Color color) 
{
    //Text Here
}
c# winforms colors header tabcontrol
4个回答
34
投票

如果要给标签加上颜色,请尝试以下代码:

this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabControl1_DrawItem);

private Dictionary<TabPage, Color> TabColors = new Dictionary<TabPage, Color>();
private void SetTabHeader(TabPage page, Color color)
{
    TabColors[page] = color;
    tabControl1.Invalidate();
}
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    //e.DrawBackground();
    using (Brush br = new SolidBrush (TabColors[tabControl1.TabPages[e.Index]]))
    {
        e.Graphics.FillRectangle(br, e.Bounds);
        SizeF sz = e.Graphics.MeasureString(tabControl1.TabPages[e.Index].Text, e.Font);
        e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + (e.Bounds.Width - sz.Width) / 2, e.Bounds.Top + (e.Bounds.Height - sz.Height) / 2 + 1);

        Rectangle rect = e.Bounds;
        rect.Offset(0, 1);
        rect.Inflate(0, -1);
        e.Graphics.DrawRectangle(Pens.DarkGray, rect);
        e.DrawFocusRectangle();
    }
}

19
投票

对于WinForms用户阅读此内容-仅当将选项卡控件的DrawMode设置为OwnerDrawFixed时,此方法才起作用-如果将DrawItem事件设置为Normal,则永远不会激发它。


8
投票

要添加到Fun Mun Pieng的答案中,该答案在Horizo​​ntal tabs上效果很好,如果您要使用Vertical tabs >>(就像我以前那样),那么您将需要以下内容:

    private void tabControl2_DrawItem(object sender, DrawItemEventArgs e)
    {
        using (Brush br = new SolidBrush(tabColorDictionary[tabControl2.TabPages[e.Index]]))
        {
            // Color the Tab Header
            e.Graphics.FillRectangle(br, e.Bounds);
            // swap our height and width dimensions
            var rotatedRectangle = new Rectangle(0, 0, e.Bounds.Height, e.Bounds.Width);

            // Rotate
            e.Graphics.ResetTransform();
            e.Graphics.RotateTransform(-90);

            // Translate to move the rectangle to the correct position.
            e.Graphics.TranslateTransform(e.Bounds.Left, e.Bounds.Bottom, System.Drawing.Drawing2D.MatrixOrder.Append);

            // Format String
            var drawFormat = new System.Drawing.StringFormat();
            drawFormat.Alignment = StringAlignment.Center;
            drawFormat.LineAlignment = StringAlignment.Center;

            // Draw Header Text
            e.Graphics.DrawString(tabControl2.TabPages[e.Index].Text, e.Font, Brushes.Black, rotatedRectangle, drawFormat);
        }
    }

如果在WinForms中,我会回显ROJO1969

的观点-那么必须将DrawMode设置为OwnerDrawFixed

特别感谢这个精彩的blog entry,它描述了如何在表单上旋转文本。


0
投票

System.Collections.Generic.KeyNotFoundException:'字典中不存在给定的键。'

© www.soinside.com 2019 - 2024. All rights reserved.