上篇说了如何创建自定义控件,接下来说说如何自定义属性,如何绘制控件,以进度控制条为例,先上效果图
这里只实现了简单的进度控制功能,该控件由三部分组成,总长度(底部白色矩形),已加载长度(灰色矩形),控制块(黑色矩形),百分比
1、首先创建一个类库,命名为MySlider, 继承自 Control 类
public class MySlider : Control
{
public MySlider()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
}
}
在构造函数中设置控件Style,ControlStyles枚举可以参考
http://technet.microsoft.com/zh-cn/subscriptions/system.windows.forms.controlstyles.aspx
2、接下来,我们需要定义以下变量,并对一些变量进行一些默认设置
Rectangle foreRect;
Rectangle backRect;
Rectangle setRect;
Color backgroundColor = Color.White;
Color foregroundColor = Color.Gray;
Color setRectColor = Color.Black;
Color fontColor = Color.Black;
int maximum = 100;
int minimum = 0;
double myValue = 0;
bool showPercent;
float fontSize = 9;
FontFamily myFontFamily = new FontFamily("宋体");
3、再来,设置属性值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
[Category("General"), Description("Show Percent Tag"), Browsable(true)]
public bool ShowPercentTag
{
get { return showPercent; }
set
{
showPercent = value;
Invalidate();
}
}
[Category("General"), Description("Control's Maximum"), Browsable(true)]
public int Maximum
{
get { return maximum; }
set
{
maximum = value;
Invalidate();
}
}
[Category("General"), Description("Control's Minimum"), Browsable(true)]
public int Minimum
{
get { return minimum; }