Creating a Rich Label
Extending the Windows.Forms.Label control.
Introduction
I was looking for a control that I could use for different kinds of headings and captions. After creating several separate controls, I decided to create just one control: a control that could be configured to have different colors, different borders, and that would respond on a mouse-action.
Structure
The best way to start doing this is to look for a good base. Instead of creating a control from scratch, I decided to inherit from the existing Windows.Forms.Label
. By doing this, I don't have to write any code to draw the text; the base control will handle this for me.
Properties
In addition to the existing properties of the Label
control, I created the following properties:
BackColor1
: This is not a new property. It is the existingBackColor
property of theLabel
control I'm inheriting from. I renamed it toBackColor1
because there will follow a secondBackColor
.BackColor2
: By using two colors, I can paint the color with a nice gradient.BackColorHover1
: When entering the control with your mouse, you can choose which color will be used for the first gradient-color. If you don't want any action, use the same color as theBackColor1
property.BackcolorHover2
: Same as the one above.BorderLeft
,BorderTop
,BorderBottom
,BorderRight
: The color of the borders of the control. Set theBorderStyle
toNone
to get this effect. I've chosen thisBorderStyle
so you can still use theFixed3D
and theFixedSingle
if you need to.Shadow
: Setting this toTrue
will draw a small white line on the left and the top side of the control. I need this when I want to create an OutlookBar-like heading. Set toFalse
if you don't like it.GradientMode
: Choose the gradient you want.GradientModeHover
: Maybe you want a different gradient when the mouse is on the control.
Methods
There's not a lot of action with this control: when entering or leaving the control with the mouse, it will use a private field IsHovering
to store the control's state. The drawing happens in the Paint
and the PaintBackGround
methods, nothing difficult about this. Take a look at the code and you will find out that it is pretty simple.
Remarks
When creating a ClassLibrary for this type of controls, don't forget to explicitly add a reference to System.Windows.Forms
and System.Drawing
, they are not included by standard! If you want to add designer-markups, use System.ComponentModel
. I have used this class to rename the existing BackColor
property to BackColor1
, and to get my new properties in the Appearance category in the Property Designer.