首页 文章

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

提问于
浏览
4

我希望在表格上有一些标签,其字体颜色与我的组框上的 Headers 相同,而且如果用户在其系统上应用了不同的主题,我希望这些颜色更改 .

我可以在不更改默认的GroupBox Headers 的情况下执行此操作吗?

更新:

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

此外,GroupBox正常行为是将FlatStyle设置为Standard将 Headers 颜色设置为ForeColor,但是要创建新的GroupBox并将其ForeColor设置为ControlText,您必须首先将其设置为ControlText以外的其他内容,然后再将其设置回来 . (如果你不遵循我的意思,那就试试吧 . )

4 回答

  • 0

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

    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;
          }
        }
    
  • 10

    从它的外观来看,GroupBox使用SystemColors.ActiveCaption绘制它的Caption,但你必须用其他主题来检查它 .

    奇怪的是,这并没有反映在ForeColor属性中,但是如果你设置了它接管的属性 .

    所以答案是:

    private void Form1_Load(object sender, EventArgs e)
    {            
      label1.ForeColor = SystemColors.ActiveCaption;
    }
    
  • 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

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

    groupBox1.ForeColor = SystemColors.ActiveBorder;
    label1.ForeColor = groupBox1.ForeColor;
    

相关问题