C# Winfrom 简单的运用Timer控件
注意,在使用DateAndTime时,需要添加引用 using Microsoft.VisualBasic;否则不可以计算时间之间的差值。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; using Microsoft.VisualBasic; namespace DJS { public partial class Form1 : Form { DateTime dtNow, dtSet; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(button1.Text=="设置") { button1.Text = "停止"; timer2.Start(); } else if(button1.Text=="停止") { button1.Text = "设置"; timer2.Stop(); label7.Text = "倒计时已取消"; } } private void timer1_Tick(object sender, EventArgs e) { label2.Text = DateTime.Now.ToLongTimeString();//显示系统时间 dtNow = Convert.ToDateTime(label2.Text); } private void timer2_Tick(object sender, EventArgs e) { //记录设置的到期时间 dtSet = Convert.ToDateTime(numericUpDown1.Value + ":" + numericUpDown2.Value + ":" + numericUpDown3.Value); long countdown = DateAndTime.DateDiff(DateInterval.Second, dtNow, dtSet, FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFourDays); if(countdown>0) { //判断倒计时是否大于0 label7.Text="倒计时已设置,剩余"+ countdown + "秒"; } else { label7.Text = "倒计时已到"; } } private void Form1_Load(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Enabled = true; numericUpDown1.Value = DateTime.Now.Hour; numericUpDown2.Value = DateTime.Now.Minute; numericUpDown3.Value = DateTime.Now.Second; } } }
Timer控件又称为计时器组件,可以定期引发事件,时间的间隔的长度用interval属性定义,其属性值为毫秒为单位,每个时间间隔会自动触发tick事件,开发人员可以在tick事件中添加要执行操作的代码