基本信息
源码名称:c#串口通信实例(支持Hex/ascii码消息发送)
源码大小:0.02M
文件格式:.zip
开发语言:C#
更新时间:2021-04-20
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
C#串口通信实例



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;//SerialPort 命名空间
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPort_bilibili
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Encoding = Encoding.GetEncoding("GB2312");   //串口编码引入GB2312编码(汉字编码)
            //防止跨线程操作空间异常
            Control.CheckForIllegalCrossThreadCalls = false;   //取消跨线程检查
        }

        //端口号扫描按钮
        private void button1_Click(object sender, EventArgs e)
        {
            ReflashPortToComboBox(serialPort1, comboBox_port);
        }

        //自动扫描可用串口并添加到串口号列表上
        private void ReflashPortToComboBox(SerialPort serialPort, ComboBox comboBox)
        {                                                               //将可用端口号添加到ComboBox
            if (!serialPort.IsOpen)//串口处于关闭状态
            {
                comboBox.Items.Clear();
                string[] str = SerialPort.GetPortNames();
                if (str == null)
                {
                    MessageBox.Show("本机没有串口!", "Error");
                    return;
                }
                //添加串口
                foreach (string s in str)
                {
                    comboBox.Items.Add(s);
                    Console.WriteLine(s);
                }
            }
            else
            {
                MessageBox.Show("串口处于打开状态不能刷新串口列表", "Error");
            }
        }