日期:2014-05-17  浏览次数:20803 次

C#.NET下设计串口终端程序+示例工程

以前一直用delphi和BCB设计和串口通信有关的软件, 不过为了与时俱进,今天在网上找了找资料,写了一个C#的串口小程序供大家参考学习.

GUI的图片:


功能的设定是非常简单的,为了大家修改成自己需要的模式,我删除了大部分不常用的功能留下了最最基础的代码.

通过选择串口,设定波特率,启动,发送字符,HEX格式切换等基本功能实现了串口通信的功能。

一下是基本代码,因为所有的代码我都简化和加了注释,所以相信是非常容易理解的。

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

namespace MyUSART
{
    public partial class MainForm : Form
    {
        bool USARTstate = true;// 串口状态 true 为可以启动 false 为可以关闭
        int RxNum = 0;
        int TxNum = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer1.Interval = 50;
            try
            {
                foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
                    this.comboBox1PortName.Items.Add(com);
                comboBox1PortName.SelectedIndex = 0;
                comboBox2BaudRate.SelectedIndex = 0;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("找不到通讯串口!", "串口提示");
            }
        }

        private void button1USARTstart_Click(object sender, EventArgs e)
        {
            if(USARTstate)//默认启动
            {
                button1USARTstart.Text = "停止";
                serialPort1.PortName = comboBox1PortName.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2BaudRate.Text);
                try
                {
                    serialPort1.Open();
                    USARTstate = false;//可以关闭
                    comboBox1PortName.Enabled = false;
                    comboBox2BaudRate.Enabled = false;
                    timer1.Enabled = true;
                }
                catch (System.Exception ex)
                {
                	MessageBox.Show("打开串口失败!\r\n:"+ex.Message);
                }
            }
            else
            {
                button1USARTstart.Text = "启动";
                try
                {
                    serialPort1.Close();
                    USARTstate = true;//可以启动
                    comboBox1PortName.Enabled = true;
                    comboBox2BaudRate.Enabled = true;
                    timer1.Enabled = false;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("关闭串口失败!\r\n:"+ex.Message);               	
                }
            }
        }



        //public static string ByteArrayToHexString(byte[] data)//字节数组转为十六进制字符串
        //{
        //    StringBuilder sb = new StringBuilder(data.Length * 3);
        //    foreach (byte b in data)
        //        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
        //    return sb.ToString().ToUpper();
        //}

        public static string ByteArrayToString(byte[] data)//字节数组转为十六进制字符串
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToChar(b));
            //return sb.ToString().ToUpper();
            return sb.ToString();
        }

        public static byte[] HexStrToHexByte(string hexStr)
        {
            hexStr = hexStr.Replace(" ", "");//去掉字符串中所有的空格
            if (hexStr.Length % 2 != 0) hexStr += " ";
            byte[] returnBytes = new byte[hexStr.Length / 2];//新建一个byte数组,存放16进制byte
            for (int i = 0; i < returnBy