一、定义容器控件时,需对该类指定相应特性
Designer(typeof(ParentControlDesigner))
二、获取或设置边框属性,如颜色、宽度、阴影、样式等等函数实现如下
//获取或设置边框宽度
float penWidth = 2;
public float PenWidth
{
get
{
return penWidth;
}
set
{
if (penWidth != value)
{
penWidth = value;
Invalidate();
}
}
}
//获取或设置顶边框颜色
Color topcolor = Color.FromArgb(45, 45, 47);
public Color PenTopColor
{
get
{
return topcolor;
}
set
{
if (topcolor != value)
{
topcolor = value;
Invalidate();
}
}
}
//获取或设置滴边框颜色
Color bottomcolor = Color.FromArgb(127, 127, 130);
public Color PenBottomColor
{
get
{
return bottomcolor;
}
set
{
if (bottomcolor != value)
{
bottomcolor = value;
Invalidate();
}
}
}
//边框绘制
private void DrawBorder(Graphics g)
{
if (penWidth > 0)
{
List points = GetPoints();
Pen pen = new Pen(topcolor, PenWidth);
g.DrawLine(pen, points[0], points[1]);
g.DrawLine(pen, points[0], points[3]);
pen.Width += 3;
pen.Color = bottomcolor;
g.DrawLine(pen, points[1], points[2]);
g.DrawLine(pen, points[3], points[2]);
pen.Dispose();
}
}
private List GetPoints()
{
List points = new List();
points.Add(new Point(0, 0));
points.Add(new Point(this.Width ,0));
points.Add(new Point(this.Width , this.Height));
points.Add(new Point(0, this.Height));
return points;
}
三、自定义Panel的初始化时,注意设置缓冲区避免闪烁感,并指定相应样式
如下
public useranel()
{
InitializeComponent();
this.SetStyle(ControlStyles.ResizeRedraw
| ControlStyles.DoubleBuffer
| ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint,
true);
this.UpdateStyles();
DoubleBuffered = true;
}
四、在重画中增加相应实现:如设置边框、颜色、宽度、阴影等等
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
DrawBorder(pe.Graphics);
}
五、实现自定义控件注意该类继承UserControl,并添加如下相关引用
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;