
Introduction
Although the article by Stephen Quattlebaum (Wrapping Win32 Controls in .NET - Horizontal and Vertical Rules) is an excellent example, I wanted to find a way to draw horizontal and vertical rules using the System.Drawing namespace.
Using the code
I first created a sealed class called drawRules. In this class, there are two public classes horizontalRule and verticalRule that inherit from Control and utilize the parameter PaintEventArgs. The hardest part of the implementation was trying to find the best color for the gray line and I finally stumbled across this color System.Drawing.KnownColor.ControlDark. Basically a gray line is drawn and then a white line is drawn off by one position to make it appear 3D like.
public class horizontalRule : Control
{
public horizontalRule(PaintEventArgs e, int x, int y, int width)
{
if (width < 0) {width = 0;}
Graphics grfx = e.Graphics;
Pen penGray = new
Pen(Color.FromKnownColor
(System.Drawing.KnownColor.ControlDark),1);
Pen penWhite = new Pen(Color.WhiteSmoke,1);
grfx.DrawLine(penGray, x, y, x+width, y);
grfx.DrawLine(penWhite, x, y+1, x+width, y+1);
}
}
public class verticalRule : Control
{
public verticalRule(PaintEventArgs e, int x, int y, int height)
{
if (height < 0) {height = 0;}
Graphics grfx = e.Graphics;
Pen penGray = new Pen(Color.FromKnownColor
(System.Drawing.KnownColor.ControlDark),1);
Pen penWhite = new Pen(Color.WhiteSmoke,1);
grfx.DrawLine(penGray, x, y, x, y+height);
grfx.DrawLine(penWhite, x+1, y, x+1, y+height);
}
}
In the form, I had to override the OnPaint method and create the horizontal and vertical rules within this method.
protected override void OnPaint(PaintEventArgs e)
{
drawRules.horizontalRule hr1 = new drawRules.horizontalRule(e,10,40,250);
drawRules.horizontalRule hr2 = new drawRules.horizontalRule(e,20,65,100);
drawRules.horizontalRule hr3 = new drawRules.horizontalRule(e,40,80,200);
drawRules.verticalRule vr1 = new drawRules.verticalRule(e,30,130,60);
drawRules.verticalRule vr2 = new drawRules.verticalRule(e,60,150,90);
drawRules.verticalRule vr3 = new drawRules.verticalRule(e,80,180,30);
}
Points of interest
A future implementation would be to handle resizing of the rules when the form is resized.
History
- October 28, 2003 - Initial release.