Click here to Skip to main content
Click here to Skip to main content

The Grouper - A Custom Groupbox Control

By , 22 Jan 2006
Rate this:
Please Sign up or sign in to vote.
Prize winner in Competition "C# Nov 2005"

Sample Image - grouperscreenshot.jpg

Introduction

The Grouper is a special group box control that is rounded and fully customizable. The control can paint borders, drop shadows, and has other features like gradient and solid backgrounds, custom text, and custom icons. The purpose of this control is to design a better looking group box WinForms control. I used the (Keep it Simple Stupid) philosophy to design a tight knitted re-useable control that I hope you all will enjoy. This control is still in beta version, but it seems to be stable.

Using the code

Before you add the control, you must add a reference (CodeVendor.Controls) to your project.

using CodeVendor.Controls;

The Grouper control can be added to your project with the following code. Add this code to your class.

private CodeVendor.Controls.Grouper Grouper1;
this.Grouper1 = new CodeVendor.Controls.Grouper();

Custom Control Properties

Below is a list of the Grouper control properties that change the physical appearance of the control.

Property Name Type Description
Control Properties
BackColor Color This feature will paint the background color of the control.
BackgroundColor Color This feature will change the group control color. This color can also be used in combination with BackgroundGradientColor for a gradient paint.
BackgroundGradientColor Color This feature can be used in combination with BackgroundColor to create a gradient background.
BackgroundGradientMode GroupBoxGradientMode This feature turns on background gradient painting.
BorderColor Color This feature will allow you to change the color of the control's border.
BorderThickness Float This feature will allow you to set the control's border size.
CustomGroupBoxColor Color This feature will paint the group title background to the specified color if PaintGroupBox is set to true.
GroupImage Image This feature can add a 16 x 16 image to the group title bar.
GroupTitle string This feature will add a group title to the control.
PaintGroupBox bool This feature will paint the group title background to the CustomGroupBoxColor.
RoundCorners int This feature will round the corners of the control.
ShadowColor Color This feature will change the control's shadow color.
ShadowControl bool This feature will allow you to turn on control shadowing.
ShadowThickness int This feature will change the size of the shadow border.
Property Name Type Description

Grouper Source Code

I started off writing this control because I was tired of the plain old Windows GroupBox. My WinForms application group box needed an updated XP look with round edges and gradient backgrounds. Like most developers writing controls, I thought to myself, should I custom draw the original GroupBox control, or reinvent the wheel and start from the ground up? I chose to reinvent the wheel Smile | :) .

Re-inventing the wheel gave me the power to draw the control without flicker and customize it to my preferences. Taking the time to make a control from the ground up seems long and futile, but having the satisfaction of knowing that I wrote the code and if anything breaks it's because of something I wrote and not someone else is fully worth it.

To start off designing the control, I had to figure out how the original GroupBox acts as a container for other controls during design mode. Below is the code for turning any control into a design-time container control:

[Designer("System.Windows.Forms.Design.ParentControlDesigner, 
           System.Design", typeof(IDesigner))]

This code must be added on top of your class as an attribute to your control, like so:

[Designer("System.Windows.Forms.Design.ParentControlDesigner, 
                        System.Design", typeof(IDesigner))]
public class Grouper : System.Windows.Forms.UserControl
{
}

Once the attribute is added to your control, the control will now automatically turn into a design-time control Container. Wow! Very easy and self contained, Microsoft sure does think of everything. The URL I found for this resource is: Microsoft support.

Since that took hardly anytime at all to add such power to my control, I decided to invest more time into where the original GroupBox left off, which was the design.

Painting a Control Without Flicker

If you are painting your own custom control, you should think about "What is the best way to paint without Flicker?". To paint without flicker, you need a way to double buffer your drawing or graphics. Microsoft has given us an option for this using control styles. The code below shows how to add double buffering to your control:

//Set the control styles----------------------------------
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
//--------------------------------------------------------

This code should be added to the constructor of your class. All of the styles are needed to create a non-flicker control. If you want to make a custom double buffer, you can create the same effect by drawing all graphics to an off-screen bitmap, and then drawing the bitmap to the screen all at once. This will virtually create the same effect as the code above. Also, notice this style:

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);

This style allows any control to support transparent colors. By default, user controls cannot support transparent colors. So you must enable this to add transparency to your back-color property.

Let's continue on with the painting of our custom painted control. To paint a user control, you need to override one of two methods depending on the desired effect. The two methods are OnPaint() and OnPaintBackground(). Below is the code to override these methods:

protected override void OnPaint(PaintEventArgs e)
{
  base.OnPaint (e);
}
        
protected override void OnPaintBackground(PaintEventArgs pevent)
{
  base.OnPaintBackground (pevent);
}

For the Grouper, we will be using the OnPaint() method. The code is shown below:

/// <SUMMARY>Overrides the OnPaint method to paint control.</SUMMARY>
protected override void OnPaint(PaintEventArgs e)
{
  PaintBack(e.Graphics);
  PaintGroupText(e.Graphics);
}

I receive the control's Graphics object from the PaintEventArgs, and pass it to my two custom methods, PaintBack() and PaintGroupText().

Creating a Rounded Control

So, you want to create a rounded custom user control? It is pretty simple to create a rounded control using the GDI+ library. Let's dive into the code to find out how it works.

/// <SUMMARY>This method will paint the control.</SUMMARY>
private void PaintBack(System.Drawing.Graphics g)
{
  //Set Graphics smoothing mode to Anit-Alias-- 
  g.SmoothingMode = SmoothingMode.AntiAlias;
  //-------------------------------------------

  //Declare Variables------------------
  int ArcWidth = this.RoundCorners * 2;
  int ArcHeight = this.RoundCorners * 2;
  int ArcX1 = 0;
  int ArcX2 = (this.ShadowControl) ? (this.Width - (ArcWidth + 1))- 
               this.ShadowThickness : this.Width - (ArcWidth + 1);
  int ArcY1 = 10;
  int ArcY2 = (this.ShadowControl) ? (this.Height - (ArcHeight + 1))-
               this.ShadowThickness : this.Height - (ArcHeight + 1);
  System.Drawing.Drawing2D.GraphicsPath path = 
                        new System.Drawing.Drawing2D.GraphicsPath();
  System.Drawing.Brush BorderBrush = new SolidBrush(this.BorderColor);
  System.Drawing.Pen BorderPen = new Pen(BorderBrush, this.BorderThickness);
  System.Drawing.Drawing2D.LinearGradientBrush BackgroundGradientBrush = null;
  System.Drawing.Brush BackgroundBrush = new SolidBrush(this.BackgroundColor);
  System.Drawing.SolidBrush ShadowBrush = null;
  System.Drawing.Drawing2D.GraphicsPath ShadowPath  = null;
  //-----------------------------------

  //Check if shadow is needed----------
  if(this.ShadowControl)
  {
    ShadowBrush = new SolidBrush(this.ShadowColor);
    ShadowPath = new System.Drawing.Drawing2D.GraphicsPath();
    ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY1+this.ShadowThickness, 
                      ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle);
                      // Top Left
    ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY1+this.ShadowThickness, 
                      ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle);
                      //Top Right
    ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY2+this.ShadowThickness, 
                      ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle);
                      //Bottom Right
    ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY2+this.ShadowThickness, 
                      ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle);
                      //Bottom Left
    ShadowPath.CloseAllFigures();

    //Paint Rounded Rectangle------------
    g.FillPath(ShadowBrush, ShadowPath);
    //-----------------------------------
  }
  //-----------------------------------

  //Create Rounded Rectangle Path------
  path.AddArc(ArcX1, ArcY1, ArcWidth, ArcHeight, 180, 
              GroupBoxConstants.SweepAngle); // Top Left
  path.AddArc(ArcX2, ArcY1, ArcWidth, ArcHeight, 270, 
              GroupBoxConstants.SweepAngle); //Top Right
  path.AddArc(ArcX2, ArcY2, ArcWidth, ArcHeight, 360, 
              GroupBoxConstants.SweepAngle); //Bottom Right
  path.AddArc(ArcX1, ArcY2, ArcWidth, ArcHeight, 90, 
              GroupBoxConstants.SweepAngle); //Bottom Left
  path.CloseAllFigures(); 
  //-----------------------------------

  //Check if Gradient Mode is enabled--
  if(this.BackgroundGradientMode==GroupBoxGradientMode.None)
  {
    //Paint Rounded Rectangle------------
    g.FillPath(BackgroundBrush, path);
    //-----------------------------------
  }
  else
  {
    BackgroundGradientBrush = 
      new LinearGradientBrush(new Rectangle(0,0,this.Width,this.Height), 
      this.BackgroundColor, this.BackgroundGradientColor, 
      (LinearGradientMode)this.BackgroundGradientMode);
                
    //Paint Rounded Rectangle------------
    g.FillPath(BackgroundGradientBrush, path);
    //-----------------------------------
  }
  //-----------------------------------

  //Paint Borded-----------------------
  g.DrawPath(BorderPen, path);
  //-----------------------------------

  //Destroy Graphic Objects------------
  if(path!=null){path.Dispose();}
  if(BorderBrush!=null){BorderBrush.Dispose();}
  if(BorderPen!=null){BorderPen.Dispose();}
  if(BackgroundGradientBrush!=null){BackgroundGradientBrush.Dispose();}
  if(BackgroundBrush!=null){BackgroundBrush.Dispose();}
  if(ShadowBrush!=null){ShadowBrush.Dispose();}
  if(ShadowPath!=null){ShadowPath.Dispose();}
  //-----------------------------------
}

The PaintBack() method above uses the GraphicsPath() method from the System.Drawing.Drawing2D class to create four arcs starting in the order of Top Left, Top Right, Bottom Right, and Bottom Left. The arcs need to be set to TopLeft: 180, TopRight: 270, BottomRight: 360 and BottomLeft: 90, with a sweep angle of 90. The CloseAllFigures() method of the GraphicsPath closes all of these arcs together for you, creating a rounded rectangle path. All that is left to do is to fill your path, using the FillPath() method. You can also choose from a solid brush or linear gradient brush for the background of the group box. To draw a border around the control, I use the DrawPath() method of the graphics library. By passing the same path to this method with a graphics pen, you can create a line border that follows the same path.

Disposing off Graphic Objects!

So many coders including myself forget to dispose() off the graphics brushes, pens, paths, colors, etc. Leaving unmanaged resources open can cause memory leaks, and will eventually slow your machine down to a dead stop. Make sure you follow these common rules whenever you are using the graphics library:

  1. Dispose off all graphic objects by calling their dispose() methods.
  2. Make sure to check that your graphics objects are not null before disposing off them.
  3. If you have common graphics objects among multiple methods, think about declaring them as class variables or constants.
  4. Don't rely on the garbage collector to auto collect your used graphic resources.

Control Improvements Needed

  • The group title bar does not size properly to an increased font size.
  • The control needs to be able to shrink to minimum height and width, without drawing over itself.
  • The group title bar needs to be able to accept icons bigger than 16 x 16, and expand to the appropriate size.
  • Some fonts have an issue reporting exact sizes when measured with the measurestring() method.
  • Option to minimize the group box, and a user button to minimize.
  • This has been completed: a background HatchBrush.
  • Custom control designer with preset options.
  • Bevel designer.
  • Drop shadow in any direction.
  • Half gradient background.
  • TypeEditor with multi-layer drawing and blending pad.

HatchBrushTypeEditor

I felt the need to design a custom type editor for hatch styles. This will be added as a selection for the Grouper's custom coloring and styles.

HatchBrushTypeEditor

Please let me know about any improvements or features you would like to see with the 1.0 version of this control.

History

  • Version 1.0 HatchBrushTypeEditor completed - January 23, 2006.
  • Version 1.0a Beta - December 17, 2005.

Screenshots

Sample screenshot

Awards

Terms and Conditions For Use, Copy, Distribution, and Modification

THIS CODE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

M@dHatter
Software Developer (Senior) Codevendor
United States United States
Please visit my personal website http://www.codevendor.com for my latest codes and updates.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 995106620-May-13 14:42 
QuestionGroupTitle Text is not centered! [modified] Pinmemberpitoloko9-Jan-13 14:44 
AnswerRe: GroupTitle Text is not alligned! [modified] Pinmemberpitoloko9-Jan-13 14:54 
Generalthanks for your design Pinmemberdongfen15-Feb-12 15:17 
GeneralMy vote of 5 PinmemberCloud Hsu5-Oct-11 21:27 
QuestionGrouper control operation PinmemberPaul G. Scannell7-Sep-11 4:43 
AnswerRe: Grouper control operation PinmemberpeteSJ5-Nov-11 13:51 
GeneralMy vote of 5 PinmemberFishbox31-Jan-11 9:49 
GeneralAutosize automatically for different images and fonts, or image only PinmemberDarryn Frost1-Sep-08 8:01 
GeneralLocalization Pinmemberladiode24-Apr-08 23:13 
GeneralRe: Localization Pinmembermarinschek16-Nov-10 22:46 
GeneralToolstrip Pinmembertcsoccerman3-Dec-07 13:51 
QuestionTabbing does not work from one RoundedGrpBox to another... Pinmemberjwah28-Nov-07 7:44 
Generaloh~~~~ very nice! thanks!!! Pinmembercnfixit6-Nov-07 7:44 
GeneralResizing the control PinmemberStevepsi20-Aug-07 13:48 
QuestionHide Group Title Pinmemberianvink@gmail.com17-Aug-07 6:18 
AnswerRe: Hide Group Title Pinmemberianvink@gmail.com17-Aug-07 7:30 
GeneralRe: Hide Group Title PinmemberAnt210011-May-09 2:19 
Generaloutlook style group box PinmemberOwfAdmin5-Aug-07 9:19 
QuestionBug with Resizing control PinmemberStevepsi14-Jun-07 11:23 
GeneralGr8 work PinmemberVikas Salvi26-May-07 1:35 
GeneralMinor bug with child controls + Autosizing GroupBar PinmemberNeil T. B.1-May-07 10:31 
GeneralFantastic Control! Pinmemberle_sloth26-Apr-07 20:53 
GeneralIt is very very nice. PinmemberKiran Beladiya12-Apr-07 18:45 
GeneralThat's ridiculously cool! PinmemberKen Hadden7-Dec-06 11:34 
Questionwhen the final version? PinmemberFabio Falsini2-Sep-06 22:29 
GeneralCrash when form minimized Pinmemberdaviddam6-Aug-06 5:05 
GeneralThanks PinmemberDarren_5-Jun-06 18:10 
QuestionLicense? PinmemberGeert van Horrik17-May-06 2:03 
AnswerRe: License? PinmemberVectorX17-May-06 5:26 
GeneralRe: License? PinmemberGeert van Horrik17-May-06 6:10 
GeneralRe: License? PinmemberJared McIntyre25-Aug-06 6:40 
GeneralThe page cannot be displayed!! PinmemberMahesh Sapre9-May-06 18:53 
GeneralNice tool + Nice article! PinmemberMahesh Sapre9-May-06 1:21 
GeneralRe: Nice tool + Nice article! PinmemberVectorX9-May-06 11:51 
QuestionUpdates?? PinmemberNelson F27-Apr-06 8:27 
AnswerRe: Updates?? PinmemberVectorX9-May-06 12:01 
QuestionRe: Updates?? PinmemberAnt210011-May-09 2:03 
GeneralNot really transparent Pinmemberrubenmch7-Apr-06 19:02 
GeneralRe: Not really transparent Pinmemberbent426-Aug-07 7:27 
Generaltransparent backgroud problem Pinmembersmanaton14-Feb-06 13:35 
GeneralRe: transparent backgroud problem PinmemberLeeNessling21-Mar-06 13:16 
GeneralProblems Pinmemberchaldon31-Jan-06 7:29 
GeneralBeta PinmemberVectorX31-Jan-06 7:43 
GeneralRe: Beta Pinmemberchaldon31-Jan-06 21:45 
Generalnext version Pinmemberhungpvtn23-Jan-06 1:28 
GeneralASP 2.0 version Pinmembercromero16-Jan-06 9:44 
GeneralRe: ASP 2.0 version PinmemberArkady Lesniara18-Jan-06 16:08 
GeneralThanks PinmemberVectorX14-Jan-06 9:53 
GeneralNice job, need a bit more work to be perfect PinmemberMichael Moreno13-Jan-06 19:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 23 Jan 2006
Article Copyright 2005 by M@dHatter
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid