编写倒计时程序代码

编写倒计时程序代码,第1张

今天小编要和大家分享的是利用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=nullPrivate 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=strTs=ts.Subtract(new TimeSpan(0,0,1))If(ts.TotalSeconds<0.0){ Time1.Enabled=false} }转至 程序员之家 http://www.sunxin.org

程序的窗体内含有两个Timer控件,一个文本框控件,两个命令按钮控件,四个标签控件。其中Timer1的Interval属性设置为60000,也就是一分钟响应一次,Timer1的Interval属性设置为500,也就是每0.5秒响应一次。Label1显示剩余时间,Label2显示现在时间。

代码如下:

Dim n As Integer

Dim t As String

Private Sub Command1_Click()'计时开始

If Text1.Text = "" Then

Exit Sub

End If

t = Val(Text1.Text)

Timer1.Enabled = True

Label1.Caption = "剩余时间:" &t &"分钟"

End Sub

Private Sub Command2_Click() '退出程序

End

End Sub

Private Sub Timer1_Timer()

n = n + 1

Label1.Caption = "剩余时间:" &t - n &"分钟"

If n = t Then

Beep

MsgBox "时间到", vbExclamation + vbOKOnly

Timer1.Enabled = False

n = 0

End If

End Sub

Private Sub Timer2_Timer()

Label2.Caption = "现在时间:" &Time

End Sub


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11046711.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存