课程名称 C#程序设计
实验名称 实验二
贰、第二题
一、实验题目
创建项目,完成“倒计时”功能,程序运行如下图所示。
二、实验要求
具体要求:
(1) 包含一个Label控件,name属性为lbltime,Text属性用来显示1小时倒计时数字;font属性分别为:黑体、40;
(2)两个button按钮,分别是“开始/暂停”、“停止”按钮;一个timer控件;
(3)除了Label,其他控件名称自定义;
(4)当单击“开始”按钮时,倒计时开始,同时“开始”按钮变为“暂停”按钮;当单击“暂停”按钮时,倒计时暂停,同时“暂停”按钮变为“开始”;当单击“停止”按钮时,倒计时停止。
所需控件及属性:
1个Label(属性Text为01:00:00,Font为黑体、40);2个Button;1个Timer(属性Interval为1000)
三、实验代码以及执行结果
1、Form1.cs:
using System;
using System.Windows.Forms;
namespace 第二题
{
public partial class Form1 : Form
{
private int totalSecond = 3599; //倒计时总时长
private int minute = 0; //分钟
private int second = 0; //秒
public Form1()
{
InitializeComponent();
}
private void timer_Tick(object sender, EventArgs e)
{//设置倒计时文本
minute = totalSecond / 60;
second = totalSecond % 60;
totalSecond--;
lbltime.Text = "00:" + minute.ToString().PadLeft(2, '0') + ":" + second.ToString().PadLeft(2, '0');
}
private void Form1_Load(object sender, EventArgs e)
{
this.timer.Interval = 1000;//设置时间间隔为1000ms
}
private void switchButton_Click(object sender, EventArgs e)
{//对开始与暂停之间的切换
if (switchButton.Text == "暂停"){
timer.Stop();
switchButton.Text = "开始";
}
else{
timer.Enabled = true;//开启timer
timer.Start();
switchButton.Text = "暂停";
}
}
private void stopButton_Click(object sender, EventArgs e)
{
timer.Stop();
}
}
}
2、执行结果:
四、实验总结
通过这次实验,我学会了如何使用timer控件实现倒计时,以及倒计时的暂停和开始的功能。
还学会了String.Padleft(Int32,Char)的用法