C# 设计倒计时器、串口助手开发

文章目录

    • [1. 实现一个简单的倒计时器开始、暂停](#1. 实现一个简单的倒计时器开始、暂停)
    • [2. 串口助手开发](#2. 串口助手开发)

1. 实现一个简单的倒计时器开始、暂停

csharp 复制代码
namespace Timer
{
    public partial class Form1 : Form
    {
        int count;//用于定时器计数
        int time;//存储设定的定时值
        bool parse = false;//控制暂停计时
        public Form1()
        {
            InitializeComponent();
        }
        //窗口创建初始化函数
        private void Form1_Load(object sender, EventArgs e)
        {
            //双击窗体后在这里给下拉框添加或者在属性items里添加都可以
            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();//提示音
                MessageBox.Show("时间到,停止计时","提示");//弹出提示框
                count = 0;
                progressBar1.Value = 0;
                comboBox1.Text = null;
            }
        }

        //开始计时按钮事件
        private void button1_Click(object sender, EventArgs e)
        {
            if (parse == true)
            {
                parse = false;
                timer1.Stop();
                return;
            }
            string str = comboBox1.Text; //将下拉框内容添加到一个变量中
            time = Convert.ToInt16(str.Substring(0,str.Length - 1)); //得到设定的定时值
            progressBar1.Maximum = time;//进度条最大数值
            parse = true;
            timer1.Start();//开始计时
        }
    }
}

2. 串口助手开发

创建项目的时候要选带(.NET Framework)的窗体应用

csharp 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialCommunicate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for(int i = 1; i < 20; i++)
            {
                comboBox1.Items.Add("COM" + i.ToString());
            }
            comboBox1.Text = "COM1";
            comboBox2.Text = "4800";
            //必须手动添加事件处理器
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        }
        
        //串口数据接收事件
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (!radioButton4.Checked)//如果为字符模式接收
            {
                string str = serialPort1.ReadExisting();//字符串方式读
                textBox1.AppendText(str);
            }
            else//数值接收
            {
                byte data;
                data = (byte)serialPort1.ReadByte();
                string str = Convert.ToString(data, 16).ToUpper();
                //空位补0
                textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox1.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//十进制数据转换
                serialPort1.Open();
                button1.Enabled = false;//打开串口按钮不可用
                button2.Enabled = true;//关闭串口
            }
            catch
            {

                MessageBox.Show("端口错误,请检查串口", "错误");
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();
                button1.Enabled = true;
                button2.Enabled = false;
            }
            catch(Exception err)//一般情况下关闭串口不会出错,所以不需要加处理程序
            {
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] Data = new byte[1];
            //判断串口是否打开
            if (serialPort1.IsOpen)
            {
                if(textBox2.Text != "")
                {
                    if (!radioButton1.Checked)
                    {
                        try
                        {
                            serialPort1.WriteLine(textBox2.Text);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show("串口数据写入错误", "错误");
                            serialPort1.Close();
                            button1.Enabled = true;
                            button2.Enabled = false;
                        }
                    }
                    else
                    {
                        //取余运算防止用户输入的字符为奇数个
                        for(int i = 0; i < (textBox2.Text.Length - textBox2.Text.Length % 2) / 2; i++)
                        {
                            Data[0] = Convert.ToByte(textBox2.Text.Substring(i * 2, 2), 16);
                            serialPort1.Write(Data, 0, 1);
                        }
                        if(textBox2.Text.Length % 2 != 0)
                        {
                            Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - 1, 1), 16);
                            serialPort1.Write(Data, 0, 1);
                        }
                    }
                }
            }
        }
    }
}
相关推荐
AIFQuant7 分钟前
贵金属 API 避坑:黄金/白银行情接口常见陷阱(数据漂移、断点、延迟)
开发语言·python·websocket·金融·restful·贵金属
加号314 分钟前
【C#】 HTTP 请求通讯实现指南
开发语言·http·c#
平安的平安26 分钟前
Python实现RAG检索增强生成:让大模型拥有你的私有知识库
开发语言·python
昵称小白29 分钟前
栈与单调栈专题
开发语言·算法
code bean37 分钟前
【LangChain】少样本提示(Few-Shot Prompting)实战指南
开发语言·python·langchain
AI人工智能+电脑小能手39 分钟前
【大白话说Java面试题 第42题】【JVM篇】第2题:JVM内存模型有哪些组成部分?
java·开发语言·jvm·面试
yqcoder40 分钟前
深入理解 JavaScript:什么是可迭代对象 (Iterable)?
开发语言·javascript·网络
破阵子4432843 分钟前
如何用 Claude Code 等 Agent 工具操作 MATLAB(支持代码编写及 Simulink)
开发语言·matlab
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题 第43题】【JVM篇】第3题:GC分为哪两种?Young GC 和 Full GC有什么区别?
java·开发语言·jvm·后端·面试