C#上位机开发串口通信编程——倒计时器开发

C#上位机开发串口通信编程——倒计时器开发

一、介绍

这是我按照B站上的一个上位机开发视频教程开发的倒计时器开发,本来只有开始计时功能,没有停止计时功能,停止计时功能后面我自己添加了。
视频网址:C#上位机开发串口通信编程——倒计时器开发

二、代码

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    
    
    public partial class Form1 : Form
    {
    
    
        int count;//用于定时器计数
        int time;//存储总的时间,定时值
        Boolean flag = true;//用于开始停止切换
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            for(int i = 1; i < 100; i++)
            {
    
    
                comboBox1.Items.Add(i.ToString() + " 秒");    
            }
            comboBox1.Text = "1 秒";
        }

        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();
                DialogResult dr = MessageBox.Show("时间到了", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dr == DialogResult.Yes)//点击是的代码
                {
    
    
                    button1.Text = "开始计时";
                    count = 0;
                    flag = true;
                    progressBar1.Value = 0;
                }
                else //点击否的代码
                {
    
    
                    button1.Text = "开始计时";
                    count = 0;
                    flag = true;
                    progressBar1.Value = 0;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            string str = comboBox1.Text;
            time = Convert.ToInt16(str.Substring(0,2));
            progressBar1.Maximum = time;
            if(flag)
            {
    
    
                    timer1.Start();
                    button1.Text = "停止计时";
                    flag = false;
                
            }else
            {
    
    
                button1.Text = "开始计时";
                flag = true;
                timer1.Stop();
                //System.Media.SystemSounds.Beep.Play();
            }
            
        }
    }
}

三、界面展示

倒计时程序界面展示

四、总结

通过这个C#入门的倒计时编程开发后,基本了解了visual studio的使用方法和开发程序的步骤,最重要的是自己把停止及时也添加后整个逻辑打通了,而且修复Bug的过程中更加熟悉了这个程序。

猜你喜欢

转载自blog.csdn.net/MamatjanPC/article/details/125816354
今日推荐