Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C#中实现倒计时功能

今天小编要和大家分享的是利用C#实现倒计时的功能,希望对大家有所帮助。本实例是通过使用timer组件来实现倒计时功能的,实现步骤如下:(1)首先创建两个窗体,在Form1窗体上添加一个Button按钮和一个timer组件,用来执行倒计时功能;在Form2中添加一个Label控件,用于显示倒计时。(2)在Form2窗体中定义一个公共变量curr_time,用于为Label控件赋值,代码如下:Public string curr_time{   Get     {        Return lable1.Text;     }  Set    {       Label1.Text=value;    }}(3)              在Form1窗体中,首先定义一个TimeSpan类对象,用于设定初始值;其次在Button按钮的Click事件下,激活timer组件,使其开始计时;然后在timer组件的Tick事件下,使用TimeSpan类对象的Subtract方法,在指定时间间隔内循环减1,实现倒计时功能。主要代码如下:Private TimeSpan ts=new TimeSpan(0,5,0);Private Form2 frm=null;Private void button1_Click(object sender,System.EventArgs e){   Timer1.Enabled =true;   Frm=new Form2();   Frm.ShowDialog(this);}Private void timer1_Tick(object sender,System.EventArgs e){   String str=ts.Hours.ToString()+”:”+ts.Minutes.ToString()+”:”+ts.Seconds.ToString();Frm.curr_time=str;Ts=ts.Subtract(new TimeSpan(0,0,1));If(ts.TotalSeconds<0.0){   Time1.Enabled=false;}