Certainly! Below is a simple example of a custom GroupBox control in C# Windows Forms where you can set the border color via a property.
csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class ColoredGroupBox : GroupBox
{
private Color borderColor = Color.Black;
public Color BorderColor
{
get { return borderColor; }
set
{
borderColor = value;
this.Invalidate(); // Redraw the control when the color changes
}
}
public ColoredGroupBox()
{
this.ForeColor = Color.Black; // Default text color
}
protected override void OnPaint(PaintEventArgs e)
{
// Draw the text
SizeF stringSize = e.Graphics.MeasureString(this.Text, this.Font);
Rectangle borderRect = new Rectangle(
0,
(int)(stringSize.Height / 2),
this.Width - 1,
this.Height - (int)(stringSize.Height / 2) - 1);
// Clear background
e.Graphics.Clear(this.BackColor);
// Draw border
using (Pen pen = new Pen(borderColor))
{
e.Graphics.DrawRectangle(pen, borderRect);
}
// Draw the text background to cover border line behind text
using (SolidBrush brush = new SolidBrush(this.BackColor))
{
e.Graphics.FillRectangle(brush, 8, 0, (int)stringSize.Width, (int)stringSize.Height);
}
// Draw the text
using (SolidBrush brush = new SolidBrush(this.ForeColor))
{
e.Graphics.DrawString(this.Text, this.Font, brush, 8, 0);
}
}
}
How to use it:
Add this class to your project.
Build the project.
The ColoredGroupBox will appear in the toolbox, or you can create it programmatically.
Set the BorderColor property to any color you want.
Example usage in a form:
csharp
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ColoredGroupBox groupBox = new ColoredGroupBox();
groupBox.Text = "Custom Border Color";
groupBox.BorderColor = Color.Red;
groupBox.Size = new Size(200, 100);
groupBox.Location = new Point(20, 20);
this.Controls.Add(groupBox);
}
}
This will create a GroupBox with a red border instead of the default system color. You can customize the BorderColor property at runtime or design time.