1、首先初始化变量
//定义Timer类变量
long TimeCount = 0;
static int interval = 1000;
System.Timers.Timer Mytimer = new System.Timers.Timer(interval);
//定义委托
public delegate void SetControlValue(long value);
2、在窗体加载函数中添加如下代码
private void Form1_Load(object sender, EventArgs e)
{
//设置重复计时
Mytimer.AutoReset = true;
//设置执行System.Timers.Timer.Elapsed事件
Mytimer.Elapsed += new System.Timers.ElapsedEventHandler(Mytimer_Tick);
Mytimer.Start();
}
Mytimer.AutoReset:true重复计时,false计时一次
Mytimer.Elapsed:触发函数,当计时到达指定时间时,触发对应函数,例如本例中时间到达一秒时,触发Mytimer_Tick()函数
Mytimer.Start():打开计时器
3、写触发函数
private void Mytimer_Tick(object sender, EventArgs e)
{
this.Invoke(new SetControlValue(ShowTime), TimeCount);
TimeCount++;
}
/// <summary>
/// 给与一个秒数,显示时间
/// </summary>
/// <param name="t"></param>
private void ShowTime(long t)
{
TimeSpan temp = new TimeSpan(0, 0, (int)t);
Time_Count.Text = string.Format("{0:00}:{1:00}:{2:00}", temp.Hours, temp.Minutes, temp.Seconds);
}
本例中当时间到1s时,Elapsed触发Mytimer_Tick函数,Mytimer_Tick触发ShowTime函数,ShowTime功能为显示文本框内容。