1.右击“解决方案项目”,添加“新建项”,选择“类库”
2..右击生成的类库“classlibrary”,添加“新建项”,选择“用户控件”
3.系统自动生成文件“BasicProgressBar.cs”,编写代码
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ClassLibrary
{
public partial class BasicProgressBar : UserControl
{
public enum TextStyleType
{
None,
Percentage,
Text,
Value,
ValueOverMaximum
};
//可变设置
private float _Value = 35;
private float _MaxValue = 100;
private float _MinValue = 0;
private float _WarningValue = 20;
private Color mercuryColor = Color.DodgerBlue; //颜色
//固定设置
private Orientation _Orientation = Orientation.Vertical;
private Color borderColor = Color.Black;
private int borderThickness = 2;
[Category("值"), Description("最大值")]
public float MaxValue
{
get
{
return _MaxValue;
}
set
{
_MaxValue = value;
}
}
[Category("值"), Description("最小值")]
public float MinValue
{
get
{
return _MinValue;
}
set
{
_MinValue = value;
}
}
[Category("值"), Description("报警值")]
public float WarningValue
{
get
{
return _WarningValue;
}
set
{
_WarningValue = value;
}
}
[Category("值"), Description("当前值")]
public float Value
{
get { return _Value; }
set
{
if (value > _MaxValue)
{
_Value = _MaxValue;
}
else if (value < _MinValue)
{
_Value = _MinValue;
}
else
{
_Value = value;
}
Invalidate();
}
}
[Category("柱型"), Description("柱型颜色")]
public Color MercuryColor
{
set
{
mercuryColor = value;
}
get
{
return mercuryColor;
}
}
public BasicProgressBar()
{
InitializeComponent();
this.SetStyle
(
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
true
);
}
private void BasicProgressBar_Paint(object sender, PaintEventArgs e)
{
if (this.Width <= 0 || this.Height <= 0)
{
return;
}
Pen pen = new Pen(borderColor, borderThickness);
e.Graphics.DrawRectangle(pen, 0, 0, this.Width, this.Height);
//Draw bar
if (_Value != 0)
{
SolidBrush brush = new SolidBrush(mercuryColor);
if (_Orientation == Orientation.Vertical)
{
int scaledHeight = this.Height - Convert.ToInt32(((double)this.Height / _MaxValue) * _Value);
e.Graphics.FillRectangle(brush, 0, scaledHeight, this.Width, this.Height);
}
else
{
int scaledWidth = Convert.ToInt32(((double)this.Width / _MinValue) * _Value);
e.Graphics.FillRectangle(brush, 0, 0, scaledWidth, this.Height);
}
}
}
}
}
4.代码编译后,系统会自动在工具控件中生成如下控件
5.使用后控件如下所示