C#winform学习小项目:倒计时器

功能:实现下拉框选择时间(5秒至500秒),启动后倒计时,途中可暂停,继续启动。

代码:

namespace test
{
    public partial class Form1 : Form
    {
        int count;//计数
        int time;//存储定时器
        bool isCount;//判断是否启动,false停止,true启动。
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for(int i = 5; i <= 500; i+=5)
            {
                comboBox1.Items.Add(i.ToString() + "秒");//下拉框
            }
            comboBox1.Text = "5秒";
            label3.Text = "0秒";
        }

        private void timer1_Tick(object sender, EventArgs e)//定时器事件
        {
            count++;
            label3.Text = (time - count).ToString() + "秒";//倒计时显示时间
            progressBar1.Value = count;//进度条进度
            if(count == time)
            {
                timer1.Stop();
                System.Media.SystemSounds.Beep.Play();//提示音效
                MessageBox.Show("时间到了!", "提示");//弹窗提示
                progressBar1.Value = 0;
                count = 0;
                isCount = false;
                button1.Text = "启动";//改按钮显示文本
            }
        }

        private void button1_Click(object sender, EventArgs e)//按钮事件
        {
            if(isCount)
            {
                //暂停
                timer1.Stop();
                button1.Text = "继续";
                isCount = false;
            }
            else
            {
                //启动、继续
                if(count == 0)
                {
                    string str = comboBox1.Text;//下拉框的取值赋值str
                    int num = str.Length - 1;
                    time = Convert.ToInt32(str.Substring(0, num));//固定长度
                    progressBar1.Maximum = time;//进度条取time
                }
                timer1.Start();
                isCount = true;
                button1.Text = "暂停";
            }

        }
    }
}

控件记录:

  • 定时器:timer    
  • 下拉框:combobox
  • 下拉框可以通过属性添加内容
  • 进度条:progressbar
  • 文本:label 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值