FWIW, this is the implementation I used. It’s a child of GroupBox but allows setting not only the BorderColor, but also the thickness of the border and the radius of the rounded corners. Also, you can set the amount of indent you want for the GroupBox label, and using a negative indent indents from the right side.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace BorderedGroupBox
{
public class BorderedGroupBox : GroupBox
{
private Color _borderColor = Color.Black;
private int _borderWidth = 2;
private int _borderRadius = 5;
private int _textIndent = 10;
public BorderedGroupBox() : base()
{
InitializeComponent();
this.Paint += this.BorderedGroupBox_Paint;
}
public BorderedGroupBox(int width, float radius, Color color) : base()
{
this._borderWidth = Math.Max(1,width);
this._borderColor = color;
this._borderRadius = Math.Max(0,radius);
InitializeComponent();
this.Paint += this.BorderedGroupBox_Paint;
}
public Color BorderColor
{
get => this._borderColor;
set
{
this._borderColor = value;
DrawGroupBox();
}
}
public int BorderWidth
{
get => this._borderWidth;
set
{
if (value > 0)
{
this._borderWidth = Math.Min(value, 10);
DrawGroupBox();
}
}
}
public int BorderRadius
{
get => this._borderRadius;
set
{ // Setting a radius of 0 produces square corners...
if (value >= 0)
{
this._borderRadius = value;
this.DrawGroupBox();
}
}
}
public int LabelIndent
{
get => this._textIndent;
set
{
this._textIndent = value;
this.DrawGroupBox();
}
}
private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =>
DrawGroupBox(e.Graphics);
private void DrawGroupBox() =>
this.DrawGroupBox(this.CreateGraphics());
private void DrawGroupBox(Graphics g)
{
Brush textBrush = new SolidBrush(this.ForeColor);
SizeF strSize = g.MeasureString(this.Text, this.Font);
Brush borderBrush = new SolidBrush(this.BorderColor);
Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);
Rectangle rect = new Rectangle(this.ClientRectangle.X,
this.ClientRectangle.Y + (int)(strSize.Height / 2),
this.ClientRectangle.Width - 1,
this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);
Brush labelBrush = new SolidBrush(this.BackColor);
// Clear text and border
g.Clear(this.BackColor);
// Drawing Border (added "Fix" from Jim Fell, Oct 6, '18)
int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;
int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;
// NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height
g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);
// Draw text
if (this.Text.Length > 0)
{
// Do some work to ensure we don't put the label outside
// of the box, regardless of what value is assigned to the Indent:
int width = (int)rect.Width, posX;
posX = (this._textIndent < 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);
posX = (posX < 0) ? rect.Width + posX - (int)strSize.Width : posX;
g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);
g.DrawString(this.Text, this.Font, textBrush, posX, 0);
}
}
#region Component Designer generated code
/// <summary>Required designer variable.</summary>
private System.ComponentModel.IContainer components = null;
/// <summary>Clean up any resources being used.</summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
components.Dispose();
base.Dispose(disposing);
}
/// <summary>Required method for Designer support - Don't modify!</summary>
private void InitializeComponent() => components = new System.ComponentModel.Container();
#endregion
}
}
To make it work, you also have to extend the base Graphics class (Note: this is derived from some code I found on here once when I was trying to create a rounded-corners Panel control, but I can’t find the original post to link here):
static class GraphicsExtension
{
private static GraphicsPath GenerateRoundedRectangle(
this Graphics graphics,
RectangleF rectangle,
float radius)
{
float diameter;
GraphicsPath path = new GraphicsPath();
if (radius <= 0.0F)
{
path.AddRectangle(rectangle);
path.CloseFigure();
return path;
}
else
{
if (radius >= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)
return graphics.GenerateCapsule(rectangle);
diameter = radius * 2.0F;
SizeF sizeF = new SizeF(diameter, diameter);
RectangleF arc = new RectangleF(rectangle.Location, sizeF);
path.AddArc(arc, 180, 90);
arc.X = rectangle.Right - diameter;
path.AddArc(arc, 270, 90);
arc.Y = rectangle.Bottom - diameter;
path.AddArc(arc, 0, 90);
arc.X = rectangle.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
}
return path;
}
private static GraphicsPath GenerateCapsule(
this Graphics graphics,
RectangleF baseRect)
{
float diameter;
RectangleF arc;
GraphicsPath path = new GraphicsPath();
try
{
if (baseRect.Width > baseRect.Height)
{
diameter = baseRect.Height;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF(baseRect.Location, sizeF);
path.AddArc(arc, 90, 180);
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 180);
}
else if (baseRect.Width < baseRect.Height)
{
diameter = baseRect.Width;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF(baseRect.Location, sizeF);
path.AddArc(arc, 180, 180);
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 180);
}
else path.AddEllipse(baseRect);
}
catch { path.AddEllipse(baseRect); }
finally { path.CloseFigure(); }
return path;
}
/// <summary>
/// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius
/// for the arcs that make the rounded edges.
/// </summary>
/// <param name="brush">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>
/// <param name="x">The x-coordinate of the upper-left corner of the rectangle to draw.</param>
/// <param name="y">The y-coordinate of the upper-left corner of the rectangle to draw.</param>
/// <param name="width">Width of the rectangle to draw.</param>
/// <param name="height">Height of the rectangle to draw.</param>
/// <param name="radius">The radius of the arc used for the rounded edges.</param>
public static void DrawRoundedRectangle(
this Graphics graphics,
Pen pen,
float x,
float y,
float width,
float height,
float radius)
{
RectangleF rectangle = new RectangleF(x, y, width, height);
GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);
SmoothingMode old = graphics.SmoothingMode;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawPath(pen, path);
graphics.SmoothingMode = old;
}
/// <summary>
/// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius
/// for the arcs that make the rounded edges.
/// </summary>
/// <param name="brush">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>
/// <param name="x">The x-coordinate of the upper-left corner of the rectangle to draw.</param>
/// <param name="y">The y-coordinate of the upper-left corner of the rectangle to draw.</param>
/// <param name="width">Width of the rectangle to draw.</param>
/// <param name="height">Height of the rectangle to draw.</param>
/// <param name="radius">The radius of the arc used for the rounded edges.</param>
public static void DrawRoundedRectangle(
this Graphics graphics,
Pen pen,
int x,
int y,
int width,
int height,
int radius)
{
graphics.DrawRoundedRectangle(
pen,
Convert.ToSingle(x),
Convert.ToSingle(y),
Convert.ToSingle(width),
Convert.ToSingle(height),
Convert.ToSingle(radius));
}
}
- Remove From My Forums
-
Question
-
Is there any way to change the border color of GroupBox ?
Thnx!
Answers
-
Hi,Kapalic
I’m not familiar with VB, but I’m able to translate it through a tool,here is the code translated:
Public Class myGroupBox
Inherits GroupBoxPrivate borderColor As ColorPublic Sub New()
MyBase.New
Me.borderColor = Color.Black
End SubPublic Property
BorderColor As Color
Get
Return Me.borderColor
End Get
Set
Me.borderColor = value
End Set
End PropertyProtected Overrides Sub
OnPaint(ByVal e As PaintEventArgs)
Dim tSize As Size = TextRenderer.MeasureText(Me.Text, Me.Font)
Dim borderRect As Rectangle = e.ClipRectangle
borderRect.Y = (borderRect.Y _
+ (tSize.Height / 2))
borderRect.Height = (borderRect.Height _
— (tSize.Height / 2))
ControlPaint.DrawBorder(e.Graphics, borderRect, Me.borderColor, ButtonBorderStyle.Solid)
Dim textRect As Rectangle = e.ClipRectangle
textRect.X = (textRect.X + 6)
textRect.Width = tSize.Width
textRect.Height = tSize.Height
e.Graphics.FillRectangle(New SolidBrush(Me.BackColor), textRect)
e.Graphics.DrawString(Me.Text, Me.Font, New SolidBrush(Me.ForeColor), textRect)
End Sub
End Class -
Open the Solution Explorer, right click on the root,choose «Add»,then «Class», name the class as «myGroupBox»,and put my code in this class, rebuild your project, the you will see a «myGroupBox» control on your toolbox, it has a «BorderColor» property on the Misc group in the property view.
Improve Article
Save Article
Improve Article
Save Article
In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp - Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:
- Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:
public virtual System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:
- Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.
// Creating a GroupBox GroupBox gbox = new GroupBox();
- Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.
// Setting the background color gbox.BackColor = Color.LemonChiffon;
- Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:
// Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control // to the GroupBox gbox.Controls.Add(c2);
Example:
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp45 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
GroupBox gbox =
new
GroupBox();
gbox.Location =
new
Point(179, 145);
gbox.Size =
new
Size(329, 94);
gbox.Text =
"Select Gender"
;
gbox.Name =
"Mybox"
;
gbox.BackColor = Color.LemonChiffon;
gbox.ForeColor = Color.Maroon;
this
.Controls.Add(gbox);
CheckBox c1 =
new
CheckBox();
c1.Location =
new
Point(40, 42);
c1.Size =
new
Size(49, 20);
c1.Text =
"Male"
;
gbox.Controls.Add(c1);
CheckBox c2 =
new
CheckBox();
c2.Location =
new
Point(183, 39);
c2.Size =
new
Size(69, 20);
c2.Text =
"Female"
;
gbox.Controls.Add(c2);
}
}
}
Output:
Improve Article
Save Article
Improve Article
Save Article
In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp - Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:
- Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:
public virtual System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:
- Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.
// Creating a GroupBox GroupBox gbox = new GroupBox();
- Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.
// Setting the background color gbox.BackColor = Color.LemonChiffon;
- Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:
// Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control // to the GroupBox gbox.Controls.Add(c2);
Example:
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp45 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
GroupBox gbox =
new
GroupBox();
gbox.Location =
new
Point(179, 145);
gbox.Size =
new
Size(329, 94);
gbox.Text =
"Select Gender"
;
gbox.Name =
"Mybox"
;
gbox.BackColor = Color.LemonChiffon;
gbox.ForeColor = Color.Maroon;
this
.Controls.Add(gbox);
CheckBox c1 =
new
CheckBox();
c1.Location =
new
Point(40, 42);
c1.Size =
new
Size(49, 20);
c1.Text =
"Male"
;
gbox.Controls.Add(c1);
CheckBox c2 =
new
CheckBox();
c2.Location =
new
Point(183, 39);
c2.Size =
new
Size(69, 20);
c2.Text =
"Female"
;
gbox.Controls.Add(c2);
}
}
}
Output:
- Remove From My Forums
-
Вопрос
-
Hi,
Am working in Visual C# Windows application. I need to change the Border color of a Groupbox.How can i achieve it ?.Thanks in advance,
Regards,
Nataraj.C-
Перемещено
Peter Ritchie
20 июня 2008 г. 13:42
off-topic
-
Перемещено
Ответы
Все ответы
-
Hi
Consider subclassing the GroupBox and manually draw the border and the title.
See the following example:public class MyGroupBox : GroupBox{
Color borderColor = Color.Red; // a fancy default colorpublic MyGroupBox() {
// to avoid flickering use double buffer
SetStyle(ControlStyles.DoubleBuffer, true);
// to force control to use OnPaint
SetStyle(ControlStyles.UserPaint, true);
}
// assign the border color
public Color BorderColor{
get{
return borderColor;
}
set{
borderColor = value;
}
}
// simple but incomplete OnPaint method, needs to draw the group box label
// and other stuff as well
protected override void OnPaint(PaintEventArgs e) {
Graphics gr = e.Graphics;
Rectangle r = new Rectangle(0, 0, Width — 1, Height — 1);
using(Brush brush = new SolidBrush(BackColor)){
using(Pen borderPen = new Pen(BorderColor)){
gr.FillRectangle(brush, r);
gr.DrawRectangle(borderPen, r);
}
}
-
And which forum would I goto to request that this feature is added to Visual Studio. It is ridiculous that I have to right code to change the border color, especially when I can change the border on just about every other standard control, and I can change the background and foreground color on this control. If nothing else, the control should change the border color to the foreground color instead of just the font foreground color.
Thanks
Evan Smith
28.12.2019C#
В Windows Forms GroupBox — это контейнер, который содержит несколько элементов управления, и элементы управления связаны друг с другом. Или, другими словами, GroupBox представляет собой рамку, отображающую группу элементов управления с подходящим необязательным заголовком. Или GroupBox используется для классификации связанных элементов управления в группе. В GroupBox вы можете установить основной цвет GroupBox в форме, используя свойство ForeColor . Вы можете установить это свойство двумя различными способами:
1. Время разработки: это самый простой способ установить цвет переднего плана GroupBox, как показано в следующих шагах:
- Шаг 1: Создайте форму окна, как показано на рисунке ниже:
Visual Studio -> Файл -> Создать -> Проект -> WindowsFormApp - Шаг 2: Затем перетащите GroupBox из панели инструментов в форму, как показано на рисунке ниже:
- Шаг 3: После перетаскивания вы перейдете к свойствам GroupBox и установите цвет переднего плана GroupBox, как показано на рисунке ниже:
Выход:
2. Время выполнения: это немного сложнее, чем описанный выше метод. В этом методе вы можете программно установить цвет переднего плана GroupBox с помощью заданного синтаксиса:
public virtual System.Drawing.Color ForeColor { get; set; }
Здесь Color указывает основной цвет GroupBox. Следующие шаги показывают, как динамически установить цвет переднего плана GroupBox:
- Шаг 1. Создание GroupBox с помощью конструктора GroupBox () предоставляется классом GroupBox.
// Creating a GroupBox GroupBox gbox = new GroupBox();
- Шаг 2. После создания GroupBox установите свойство ForeColor для GroupBox, предоставляемого классом GroupBox.
// Setting the foreground color gbox.ForeColor = Color.Maroon;
- Шаг 3. И, наконец, добавьте этот элемент управления GroupBox в форму, а также добавьте другие элементы управления в GroupBox, используя следующие операторы:
// Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control to the GroupBox gbox.Controls.Add(c2);
Пример:
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp45 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
GroupBox gbox =
new
GroupBox();
gbox.Location =
new
Point(179, 145);
gbox.Size =
new
Size(329, 94);
gbox.Text =
"Select Gender"
;
gbox.Name =
"Mybox"
;
gbox.BackColor = Color.LemonChiffon;
gbox.ForeColor = Color.Maroon;
this
.Controls.Add(gbox);
CheckBox c1 =
new
CheckBox();
c1.Location =
new
Point(40, 42);
c1.Size =
new
Size(49, 20);
c1.Text =
"Male"
;
gbox.Controls.Add(c1);
CheckBox c2 =
new
CheckBox();
c2.Location =
new
Point(183, 39);
c2.Size =
new
Size(69, 20);
c2.Text =
"Female"
;
gbox.Controls.Add(c2);
}
}
}
Выход:
Рекомендуемые посты:
- Как установить цвет фона GroupBox в C #?
- Как установить основной цвет метки в C #?
- Как установить цвет переднего плана ComboBox в C #?
- Как установить основной цвет кнопки в C #?
- Как установить основной цвет RadioButton в C #?
- Как установить цвет переднего плана ListBox в C #?
- Как установить цвет переднего плана FlowLayoutPanel в C #?
- Как установить основной цвет для NumericUpDown в C #?
- Как установить цвет переднего плана MaskedTextBox в C #?
- Как установить цвет переднего плана RichTextBox в C #?
- Как установить цвет переднего плана TextBox в C #?
- Как установить цвет переднего плана CheckBox в C #?
- C # | Как изменить основной цвет текста в консоли
- Как установить имя GroupBox в C #?
- Как установить видимость GroupBox в C #?
Как установить цвет переднего плана GroupBox в C #?
0.00 (0%) 0 votes
|
Автор | Тема: Как изменить цвет QGroupBox? (Прочитано 10116 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||