winforms倒计时器程序

本文详细描述了一个WindowsForms应用程序,展示了如何使用C#编程实现一个计时器功能,包括秒数选择、计时显示、剩余时间和计时结束的提示。
摘要由CSDN通过智能技术生成
using System;
using System.Windows.Forms;

namespace WindowsForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Text = "开始计时";
            label1.Text = "时长";
            label2.Text = "剩余时间";

            timer1.Interval = 1000;

            for(int i = 1;i < 100;i++)  // 时长计数范围1-99秒
            {
                comboBox1.Items.Add($"{i} 秒");
            }
            comboBox1.SelectedIndex = 0;

        }

        // 开始计时按钮事件
        // 用户选择和初始化计时的逻辑放在 button1_Click 事件处理器里
        // 只需在按下按钮的时候才去获取一下comboBox1的值,而timer1_Tick每隔1秒就执行一次,没必要每隔1秒就获取一次comboBox1
        private void button1_Click(object sender, EventArgs e)
        {
            string str = comboBox1.Text;
            string data = str.Substring(0, 2);
            time = Convert.ToInt16(data);  // 提取出前两位字符并转换为Int  将结果赋值给time

            progressBar1.Maximum = time;//设置进度条最大数值
            count = 0;
            timer1.Start();//开始计时
        }

        // 文本 时长
        private void label1_Click(object sender, EventArgs e)
        {

        }

        // 文本 剩余时间
        private void label2_Click(object sender, EventArgs e)
        {

        }

        // 剩余时间(秒)
        private void label3_Click(object sender, EventArgs e)
        {
        }
        
        // (时长)下拉框事件
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label3.Text = comboBox1.SelectedItem.ToString();
        }

        // 进度条
        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        int count;
        int time;

        // 定时器事件  只处理计时逻辑  每隔1000毫秒会被调用。
        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.Asterisk.Play();//播放提示音
                MessageBox.Show("时间到了!", "提示");
            }

        }
    }
}

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值