如何设置标签的字体颜色与GroupBox的标题颜色相同?

How do I set the Font color of a label to the same as the caption color of a GroupBox?

提问人:Patrick McDonald 提问时间:2/26/2009 最后编辑:Patrick McDonald 更新时间:2/27/2009 访问量:34051

问:

我希望在表单上有一些标签,其字体颜色与组框上的标题相同,此外,如果用户在其系统上应用了不同的主题,我希望这些颜色会更改。

是否可以在不更改 GroupBox 标题的默认值的情况下执行此操作?

更新:

我尝试将 Label ForeColor 设置为 ActiveCaption,这对于默认(蓝色)方案看起来没问题,但是当我将方案更改为 Olive Green 时,标签和组框标题并不相同。

此外,GroupBox 的正常行为是将 FlatStyle 设置为 Standard 会将标题颜色设置为 ForeColor,但是若要创建新的 GroupBox 并将其 ForeColor 设置为 ControlText,必须先将其设置为 ControlText 以外的其他内容,然后再将其设置回来。(如果你不理解我的意思,那就试试看吧。

C# .NET vb.net WinForms

评论

0赞 nawfal 9/21/2011
我遇到了同样的麻烦!

答:

0赞 BFree 2/26/2009 #1

该标签公开 ForeColorChanged 事件。然后,您可以执行如下操作:

this.label1.ForeColorChanged += (o,e) => { this.groupBox1.ForeColor = this.label1.ForeColor;};

但是,如果尝试检测用户何时更改其主题,则可以挂接到可在 Microsoft.Win32 命名空间中找到的 SystemEvents。像这样的东西:

    Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);

void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
        {
            this.groupBox1.ForeColor = this.label1.ForeColor;
        }
0赞 Andreas 2/26/2009 #2

我假设您使用的是 Windows 窗体而不是 WPF。当您应用颜色时,使用系统颜色(例如 Control 或 HighlightText),当用户切换 Windows 主题时,这些颜色将更改。下面是将组框的颜色设置为系统颜色,然后将此颜色应用于标签的代码:

groupBox1.ForeColor = SystemColors.ActiveBorder;
label1.ForeColor = groupBox1.ForeColor;
10赞 Hans Passant 2/27/2009 #3

嗯,同样的问题?我会重复我的帖子:

using System.Windows.Forms.VisualStyles;
...

    public Form1()
    {
      InitializeComponent();
      if (Application.RenderWithVisualStyles)
      {
        VisualStyleRenderer rndr = new VisualStyleRenderer(VisualStyleElement.Button.GroupBox.Normal);
        Color c = rndr.GetColor(ColorProperty.TextColor);
        label1.ForeColor = c;
      }
    }

评论

0赞 Patrick McDonald 2/27/2009
不同的问题,我的另一个问题(stackoverflow.com/questions/590637/...)是关于如何更改组框上标题的颜色。我喜欢这个答案,但只是作为这个问题的答案,而不是另一个答案。