日期:2012-02-11  浏览次数:20400 次

以前用Delphi开发软件的时候,如果需要在界面上放置一个分隔线,其自带的TBevel可以很好地满足这一要求。现在转到了.NET平台,竟找不到对应的控件(毕竟每次在Paint事件中画太麻烦)。而如果用Panel、GroupBox、Label来间接实现,效果不够理想,并且感觉怪怪的。因此决定自己实现一个分隔线控件,效果如下图所示:








  在这里我只将核心代码贴出来,关于创建自定义控件的相关知识可参考MSDN:

ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/vbcon/html/vbconControlCreation.htm



/// <summary>

/// 水平分隔线

/// </summary>

[

ToolboxBitmap(typeof(LineH), "res.LineH.ico"),

Designer(typeof(LineHDesigner))

]

public class LineH : System.Windows.Forms.UserControl

{
//... ...



private void LineH_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

{

Graphics g = e.Graphics;

Rectangle r = this.ClientRectangle;



Pen darkPen = new Pen(SystemColors.ControlDark, 1);

Pen LightPen = new Pen(Color.White);



//用暗色调处理上边缘

g.DrawLine(darkPen, r.Left, r.Top, r.Right, r.Top);



//用亮色调处理下边缘

g.DrawLine(LightPen, r.Left, r.Top + 1, r.Right, r.Top + 1);

}


//... ...

}




/// <summary>

/// 垂直分隔线

/// </summary>

[

ToolboxBitmap(typeof(LineV), "res.LineV.ico"),

Designer(typeof(LineVDesigner))

]

public class LineV : System.Windows.Forms.UserControl

{
//... ...



private void LineV_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

{

Graphics g = e.Graphics;

Rectangle r = this.ClientRectangle;



Pen darkPen = new Pen(SystemColors.ControlDark, 1);

Pen lightPen = new Pen(Color.White);



//用暗色调处理左边缘

g.DrawLine(darkPen, r.Left, r.Top, r.Left, r.Bottom);



//用亮色调处理右边缘
g.DrawLine(lightPen, r.Left + 1, r.Top, r.Left + 1, r.Bottom);

}

//... ...

}





欲完全实现上图所示效果,可参阅http://blog.csdn.net/doubon/archive/2005/01/18/258314.aspx。