目的:实现秒的倒计时功能
目录
1、Form窗体设计
整体展示:
定时时间:ComboBox 剩余时间:Lable 进度条:ProgerssBar 计时器:Timer
开始计时、暂停计时、停止计时:Button
2、设计思路
1).ComboBox下拉框的数据填充。通过for循环0-100的整数来填充下拉框。
2).倒计时的原理。通过设定的定时时间-计时器的计时=剩余时间。
3).Button的禁用和启用以及其他参数的初始化。
a、初始化三个按钮都是禁用状态,ComboBox为未选中状态。ProgerssBar进度条为最大位置。
b、当定时时间为未选中时,开始计时按钮是禁用状态。
c、当剩余时间Lable没有数值时,暂停和停止计时是禁用状态。
4).开始计时:a、点击开始计时,将定时时间的数值赋给剩余时间。
b、将定时时间的值赋给ProgerssBar进度条的最大值。
c、启动计时器。
5).定时器事件:a、剩余时间=将计时器的数值-定时时间。
b、ProgerssBar进度条的值=进度条最大值-计时器数值。
c、当计时器数值=定时时间时,计时器计数清零、弹窗提醒倒计时结束、计时器停止。
6).暂停计时:停止计时器计时。再次点击开始计时,继续暂停前的倒计时。
7).停止计时:计时器清零、定时时间恢复到未选中的状态、剩余时间为空、进度条为最大 值、计时器停止工作。
3、源码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace timer_Dmeo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//初始化
cbo_TimeSet.SelectedIndex = -1;
btn_Start.Enabled = false;
btn_Stop.Enabled = false;
btn_Suspend.Enabled = false;
pro_Time.Value = pro_Time.Maximum;
}
int count; //系统定时器计数
int time; //定时时间
private void Form1_Load(object sender, EventArgs e)//窗体创建后运行的函数(Load)
{
for (int i = 0; i < 100; i++)
{
cbo_TimeSet.Items.Add(i.ToString()+"秒");//向下拉框添加数据0-100
}
}
//计时器
private void timer1_Tick(object sender, EventArgs e)
{
count++;//自加1
lbl_Surplus.Text = ((time - count)*0.1).ToString()+"秒"; //剩余时间开始显示
pro_Time.Value = pro_Time.Maximum-count;
if (count == time)
{
btn_Stop_Click(null,null);
timer1.Stop(); //停止计时
count = 0;
MessageBox.Show("倒计时结束!");
}
}
//开始计时
private void btn_Start_Click(object sender, EventArgs e)
{
string temp = cbo_TimeSet.Text.Trim(); //将comBox选择的数据赋值给剩余时间
time = Convert.ToInt16(temp.Substring(0,2))*10;
pro_Time.Maximum = time;
timer1.Start();//计时器开始计时
}
//暂停计时
private void btn_Suspend_Click(object sender, EventArgs e)
{
timer1.Stop();//停止计时器
}
//停止计时
private void btn_Stop_Click(object sender, EventArgs e)
{
count = 0;//计时器计数清零
this.cbo_TimeSet.SelectedIndex = -1; //设定时间恢复到未选择状态
lbl_Surplus.Text = string.Empty; //倒计时恢复空值
pro_Time.Value = pro_Time.Maximum;
timer1.Stop(); //计时器停止工作
}
#region Button按钮的禁用
private void lbl_Surplus_TextChanged(object sender, EventArgs e)
{
if (lbl_Surplus.Text.Length == 0)
{
btn_Suspend.Enabled = false; btn_Stop.Enabled = false;
}
else
{
btn_Suspend.Enabled = true; btn_Stop.Enabled = true;
}
}
private void cbo_TimeSet_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbo_TimeSet.SelectedIndex == -1)
{
btn_Start.Enabled = false;
}
else
{ btn_Start.Enabled = true; }
}
#endregion
}
}