在windows Form中,从头开始定义一个控件需要了解很多的底层技术细节,其工作量相当可观。所以,应尽量选择从现有的控件中派生,或者组合现有的控件为一个新的控件。
拥有计时功能的进度条控件:
windows窗体控件库,制作一个进度条控件(利用现有的进度条和timer控件),生成后会自动添加到工具箱中:
自制控件代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsControlLibrary1
{
public delegate void TimeIsUpDelegate();//事件委托
public partial class TimeProgressBar: UserControl
{
public event TimeIsUpDelegate TimeIsUp;//“时间到”事件
public TimeProgressBar()
{
InitializeComponent();
timer1.Tick += new EventHandler(Begin);
timer1.Enabled = false;
}
private double TotalSeconds = 0;//计时总时间(按秒),用于计算完成比例
private TimeSpan TotalTime;//计时总时间
private DateTime BeginTime; //计时起始时间
/// <summary>
/// 设置计时长度
/// </summary>
/// <param name="hour">小时</param>
/// <param name="minute">分钟</param>
/// <param name="second">秒</param>
public void SetTimeSpan(int hour,int minute,int second)
{
TotalTime = new TimeSpan(hour,minute,second);
TotalSeconds = TotalTime.TotalSeconds;
this.Initialize();
}
private void Initialize()
{
BeginTime = DateTime.Now;
progressBar1.Value = 0;
timer1.Enabled = true;
}
//开始计时
private void Begin(Object sender,EventArgs e)
{
TimeSpan ElapsedTime = (DateTime.Now - BeginTime);
int temp=(int)(ElapsedTime.TotalSeconds/TotalSeconds*100);
if (temp>progressBar1.Maximum)
{
temp = progressBar1.Maximum;
}
progressBar1.Value = temp;
if (ElapsedTime>=TotalTime)
{
timer1.Enabled = false;
if (TimeIsUp!=null)
{
TimeIsUp();
}
}
}
}
}
利用控件计时20秒:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timeProgressBar1_TimeIsUp()
{
MessageBox.Show("Time Is Up!");
}
private void button1_Click(object sender, EventArgs e)
{
timeProgressBar1.SetTimeSpan(0,0,20);
//timeProgressBar1.SetTimeSpan(Convert.ToInt32(label1.Text), Convert.ToInt32(label2.Text), Convert.ToInt32(label3.Text));
//timeProgressBar1.SetTimeSpan(Convert.ToInt32(domainUpDown1.Text), Convert.ToInt32(domainUpDown2.Text), Convert.ToInt32(domainUpDown3.Text));
}
}
}
另一个例程,可统计单击次数的自定义按钮:
稍后再更新...