One of our applications required a GroupBox which was more like
the one featured in the Options dialog of Microsoft Outlook
2003. This article describes how to create a custom GroupBox
component which allows this type of user interface, and also a
neat trick on adjusting the client area so that when you drag
controls inside the GroupBox, the handy little margin guides
allow you to position without overlapping the icon.
Add a new Component class to your project, and inherit this
from the standard GroupBox.
I personally don't like assigning variables at the same time as
defining them, so I've added a default constructor to assign the
defaults and also to set-up the component as we need to set a
Although this is a simple component, we need at the minimum an
Image property to specify the image. We're also adding color
properties in case we decide to use the component in a
non-standard interface later on.
If you wanted you could create and destroy required GDI objects
every time the control is painted, but in this example I've
opted to create them once for the lifetime of the control.
Therefore I've added CreateResources and CleanUpResources to
create and destroy these. Although not demonstrated in this
in-line listing, CleanUpResources is also called from the
components Dispose method. You'll also notice
CreateResources is called whenever a property value changes,
and that it first releases resources in use.
Now that all the initialization is performed, we're going to add
our drawing routine which is to simply override the OnPaint
Remember that as we are overriding an existing component, we
should override the base components methods whenever possible -
this means overriding OnPaint and not hooking into the
In the code above you'll also notice a block specifically for
design time. As this control only has borders at the top of the
control, at design time it may not be obvious where the
boundaries of the control are when laying out your interface.
This code adds a dotted outline to the control at design time,
and is ignored at runtime.
Another method we are overriding is OnSystemColorsChanged.
As our default colors are based on system colors, should these
change we need to recreate our objects and repaint the control.
The client area of a standard group box accounts for the text
header and the borders. Our component however, needs an
additional offset on the left to account for the icon. If you
try and place controls into the group box, you will see the
snapping guides appear in the "wrong" place.
Fortunately however, it is very easy for us to suggest our own
client area via the DisplayRectangle property. We just
override this and provide a new rectangle which includes
provisions for the width of the image.
Now as you can see the snapping guides suggest a suitable left
margin based on the current image width.
You can download the complete source for the GroupBox