串口读写测试

1.下载VSPD虚拟串口破解版下载6.9 汉化版

串口读写测试_第1张图片

 

2.C#界面

串口读写测试_第2张图片

3.source

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

namespace ReadSerialPort
{
    public partial class Form1 : Form
    {

        delegate void UpdateTextEventHandler(string text); //委托,关键所在
        UpdateTextEventHandler UpdateTextEventHandler1;

        public Form1()
        {
            InitializeComponent();
        }

        private void OpenPort()
        {           
            try
            {
                this.UpdateTextEventHandler1 = new UpdateTextEventHandler(this.getCOM1); // 实例化委托对象
                this.serialPort1.Open();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.serialPort1.Close();
            }
            try
            {
                this.serialPort2.Open();
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                this.serialPort2.Close();
            }
        }
            

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenPort();
            this.comboBox1.Items.AddRange(SerialPort.GetPortNames());
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.serialPort1.Close();
            this.serialPort2.Close();
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string readString = this.serialPort1.ReadLine();
            this.Invoke(UpdateTextEventHandler1, new string[] { readString });
        }

        private void getCOM1(string text)
        {
            if (this.serialPort1.IsOpen)
                this.txtReceive.Text = this.txtReceive.Text + "\r\n" + text;

        }


        private void btnSend_Click(object sender, EventArgs e)
        {
            if (this.serialPort2.IsOpen)
                this.serialPort2.WriteLine(this.txtSend.Text.Trim());
        }

    }
}

 

你可能感兴趣的:(串口读写测试)