Here’s a drop-in replacement for the standard GroupBox that exposes a BorderColor property. Just add this class to your project, compile, and you’ll get a GroupBox whose border you can tint any color you like.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace YourNamespace
{
public class ColoredGroupBox : GroupBox
{
private Color _borderColor = Color.Black;
[Category("Appearance")]
[Description("The color of the group box border.")]
public Color BorderColor
{
get => _borderColor;
set
{
_borderColor = value;
Invalidate(); // repaint on change
}
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
e.Graphics.TextRenderingHint =
System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
// Measure the size of the caption text
SizeF textSize = e.Graphics.MeasureString(Text, Font);
int textHeight = (int)textSize.Height;
int textWidth = (int)textSize.Width;
// Calculate the rectangle in which we'll draw the border
int halfTextHeight = textHeight / 2;
Rectangle borderRect = new Rectangle(
0,
halfTextHeight,
this.Width - 1,
this.Height - halfTextHeight - 1
);
using (var pen = new Pen(_borderColor))
{
// Draw left vertical line
e.Graphics.DrawLine(pen,
borderRect.Left, borderRect.Top,
borderRect.Left, borderRect.Bottom);
// Draw bottom horizontal line
e.Graphics.DrawLine(pen,
borderRect.Left, borderRect.Bottom,
borderRect.Right, borderRect.Bottom);
// Draw right vertical line
e.Graphics.DrawLine(pen,
borderRect.Right, borderRect.Bottom,
borderRect.Right, borderRect.Top);
// Draw top line in two segments (to leave space for text)
int textPadding = 6;
e.Graphics.DrawLine(pen,
borderRect.Left, borderRect.Top,
borderRect.Left + textPadding, borderRect.Top);
e.Graphics.DrawLine(pen,
borderRect.Left + textPadding + textWidth,
borderRect.Top,
borderRect.Right, borderRect.Top);
}
// Finally draw the caption text
var textRect = new Rectangle(
textPadding, 0,
textWidth, textHeight
);
TextRenderer.DrawText(
e.Graphics,
Text,
Font,
textRect,
ForeColor,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter
);
}
}
}
How to use it:
- Build your project so the new control appears in the Toolbox.
- Drag & drop
ColoredGroupBox onto your form (or instantiate it in code).
- In the Properties window you’ll now see
BorderColor—pick any color you like!
Example in code:
var grp = new ColoredGroupBox();
grp.Text = "Options";
grp.BorderColor = Color.Teal;
grp.Size = new Size(200, 120);
grp.Location = new Point(10, 10);
this.Controls.Add(grp);
🎨 Enjoy your colorful GroupBoxes!