平时在做c#项目时偶尔会碰到要使用进度条的情况,但c#自带的进度条外观往往不合我们心意,这就需要我们自己动手来只做一款自己的进度条。先上图:
外观虽然简单,但感觉比c#自带的好看多了。
绘制这样一个进度条需要两个基本控件,两个Label,一个picturebox,下面是myProgressBar类的代码
public class myProgressBar
{
public PictureBox picFocus;
public Label lbltop;
public Label lblbottom;
int value = 0;
int x1;
int y1;
int h1;
int w1;
Form f1;
public myProgressBar(Form f, int x, int y, int width, int high)
{
//绘制进度条,用两个label以及一个picturebox组合为进度条
lblbottom = new Label();
lbltop = new Label();
lblbottom.BackColor = Color.Gray;
lbltop.BackColor = Color.Yellow;
//进度条上的光标
picFocus = new PictureBox();
picFocus.Size = new Size(high+6, high+6 );
picFocus.Location = new Point(x + value, y - 3);
picFocus.BackgroundImage = Image.FromFile("yellowyuan.png");
picFocus.BackgroundImageLayout = ImageLayout.Stretch;
picFocus.BackColor = Color.Transparent;
lblbottom.SetBounds(x, y, width, high);
lbltop.Size = new Size(value, high);
lblbottom.Controls.Add(lbltop);
f.Controls.Add(picFocus);
f.Controls.Add(lblbottom);
x1 = x;
y1 = y;
h1 = high;
w1 = width;
f1 = f;
}
public void updateFocus(int value)
{
picFocus.Location = new Point(x1 + value, y1 - 3);
lbltop.Size = new Size(value, h1);
}
//进度条拖动
Point clickPoint;
public bool isDrag;
internal void picFocus_MouseDown(object sender, MouseEventArgs e)
{
isDrag = true;
clickPoint = new Point(e.X, e.Y);
}
int offsetX;
internal void picFocus_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
offsetX = e.X - clickPoint.X;
//若进度条没有超出可拖动范围
if (picFocus.Location.X >= lblbottom.Location.X && picFocus.Location.X <= lblbottom.Location.X + w1 - picFocus.Width)
{
picFocus.Location = new Point(picFocus.Location.X + offsetX, picFocus.Location.Y);
}
//若进度条超出最小范围,将他置于最小位置
if (picFocus.Location.X < lblbottom.Location.X)
{
picFocus.Location = new Point(lblbottom.Location.X, picFocus.Location.Y);
}
//若进度条超出最大范围,将他置于最大位置
if (picFocus.Location.X > lblbottom.Location.X + w1 - picFocus.Width)
{
picFocus.Location = new Point(lblbottom.Location.X + w1 - picFocus.Width, picFocus.Location.Y);
}
//改变lbltop长度
int value = picFocus.Location.X - lblbottom.Location.X;
this.updateFocus(value);
}
}
internal void picFocus_MouseUp(object sender, MouseEventArgs e)
{
isDrag = false;
}
然后在Form中添加load事件,并填写如下代码:
private void Form1_Load(object sender, EventArgs e)
{
//生成进度条
myProgressBar mbp = new myProgressBar(this,200,200,200,8);
this.Controls.Add(mbp.picFocus);
this.Controls.Add(mbp.lblbottom);
//注册进度条拖动事件
mbp.picFocus.MouseDown += new MouseEventHandler(mbp.picFocus_MouseDown);
mbp.picFocus.MouseMove += new MouseEventHandler(mbp.picFocus_MouseMove);
mbp.picFocus.MouseUp += new MouseEventHandler(mbp.picFocus_MouseUp);
}
OK,大功告成!