Search code examples
vb.netwinformsgroupbox

How can I change the ForeColor of the GroupBox text without changing its children ForeColor?


I want to know if there is an option to just change the color of group box text at the top left of the group box in a windows form and not any controls or labels located inside of the group box.

I know that GroupBox.ForeColor = Color.Blue will change all text associated with that box to blue, but it also changes the ForeColor of labels and other controls in the GroupBox.

How can I change the color of the group box text without changing its children forecolor?


Solution

  • The ForeColor property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control.

    Since you didn't set ForeColor for the labels and textboxes in the group box, they will use ForeColor value of their parent. You can solve this problem using either of these options:

    1. Put a Panel in GroupBox Set the ForeColor of GroupBox to Blue and set ForeColor of Panel to ControlText explicitly using designer. Then put other controls in the Panel. This way, your controls will use ForeColor of Panel which you set explicitly.

    2. Customize Paint of GroupBox:

      Private Sub GroupBox1_Paint(ByVal sender As System.Object, _
          ByVal e As System.Windows.Forms.PaintEventArgs) Handles GroupBox1.Paint
      
          e.Graphics.Clear(Me.GroupBox1.BackColor)
          GroupBoxRenderer.DrawGroupBox(e.Graphics, Me.GroupBox1.ClientRectangle, _
              Me.GroupBox1.Text, Me.GroupBox1.Font, Color.Blue, _
              System.Windows.Forms.VisualStyles.GroupBoxState.Normal)
      End Sub