C# 设计一个倒计时程序,需要在文本框中输入倒计时分钟数。用Windows窗体设计
namespace CountDown
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int timeData = 0;//时间数据变量,以秒为单位
bool btFlag = true;//计时器标签
private void button1_Click(object sender, EventArgs e)
{
if (btFlag)//如果是启动计时器标签为true
{
if (timeData>= 0)
{
ShowTimeLabel(ref timeData);//显示具体是时间数
timer1.Start();//启动计时器
button1.Text = "停止计时";
btFlag = false;
}
}
else
{
timer1.Stop();//关闭计时器
button1.Text = "启动计时器";
btFlag = true;
}
}
/// <summary>
/// 把时间显示为时分秒的格式
/// </summary>
/// <param name="timeData"></param>
private void ShowTimeLabel(ref int timeData)
{
string hourStr = (timeData / 3600).ToString();
string minuteStr ="0";
string secondStr = "0";
//label2.Text = hourStr + " 小时 " + (timeData % 60).ToString()+" 分钟";
if (timeData % 3600 >= 60)
{
minuteStr = ((timeData % 3600) / 60).ToString();
secondStr = ((timeData % 3600) % 60).ToString();
}
else
{
secondStr = ((timeData % 3600) % 60).ToString();
}
label2.Text = hourStr + "小时" + minuteStr + "分钟" + secondStr + "秒";
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);//添加计时器的tick事件
button1.Text = "启动计时器";
btFlag = true;
textBox1.TextChanged += new EventHandler(textBox1_TextChanged);//添加事件
}
void textBox1_TextChanged(object sender, EventArgs e)
{
timer1.Stop();
label2.Text = string.Empty;
try
{
if(textBox1.Text!=string.Empty)
timeData = Convert.ToInt32(textBox1.Text) * 60;
}
catch
{
MessageBox.Show("请输入合法数据","温馨提示");
textBox1.Text = string.Empty;
}
button1.Text = "启动计时器";
btFlag = true;
}
void timer1_Tick(object sender, EventArgs e)
{
timeData--;//时间数减一秒
ShowTimeLabel(ref timeData);
if (timeData == 0)
{
timer1.Stop();
}
}
}
}
2024-07-20 广告