本文转自http://www.codeproject.com/KB/miscctrl/NiceLine.aspx
Introduction
NiceLine is a pretty simple line that can be used to separate controls on a form or to make a title with a color background effect. The same effect can be obtained with 2 colored lines but is easier to just drag-drop this control on a form.
The code
The C# control class NiceLine
is derived from System.Windows.Forms.UserControl
. It overrides the OnPaint
method to draw itself.
The main part of the code will draw the lines depending on the properties set (alignment, text caption, etc.)
// -------
// | ...caption...
e.Graphics.DrawLines(new Pen(Color.DimGray, 1),
new Point[] {
new Point(0, ym + 1),
new Point(0, ym),
new Point(beforeCaption, ym)
}
);
There are 5 properties that modify the appearance of NiceLine:
Caption
- represents the caption text displayed on the line. If the caption is "" (the default) the line is not brokenCaptionMarginSpace
- represents the distance in pixels form the control margin to caption textCaptionPadding
- represents the space in pixels around text captionCaptionOrizontalAlign
- will tell where the text caption is aligned in the control. Can beLeft
,Center
orRight
LineVerticalAlign
- represent the vertical alignment of the line within the space of the control. Can beTop
,Middle
orBottom
/// <SUMMARY>
/// The space in pixels around text caption
/// </SUMMARY>
[Category("Appearance")]
[DefaultValue(2)]
[Description("The space in pixels around text caption")]
public int CaptionPadding
{
get { return _CaptionPadding; }
set
{
_CaptionPadding = value;
Invalidate();
}
}
The LineVerticalAlign
property require some explications. The necessity arrived because the control has a height that depend on the font chosen (to allow the text to be drown).
protected override void OnResize(System.EventArgs e)
{
base.OnResize(e);
this.Height = this.Font.Height + 2;
this.Invalidate();
}
So the line is drawn by default to the middle of the control but this can be changed with LineVerticalAlign
property.
Title with background effect
This effect can be achieved using a Panel
with the background color changed (in demo it's white), a colored label and a NiceLine
control with LineVerticalAlign
set to Top
.
Transparent background
At the beginning I tried to make a transparent background (thus the LineVerticalAlign
property is not necessary to make the title effect) but I ran in some problems in design mode (the control was not paining itself every time) so I decided to remove this. The code is still in the class (commented).