C# 定时通讯的高速串口的编程框架

发布于:2024-12-06 ⋅ 阅读:(205) ⋅ 点赞:(0)

C# 定时通讯的高速串口的编程框架

using System;
using System.IO.Ports;
using System.Windows.Forms;
 
namespace SerialPortExample
{
    public partial class MainForm : Form
    {
        private SerialPort serialPort = new SerialPort();
 
        public MainForm()
        {
            InitializeComponent();
            InitializeSerialPort();
        }
 
        private void InitializeSerialPort()
        {
            serialPort.PortName = "COM3"; // 请根据实际情况修改
            serialPort.BaudRate = 9600;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.Handshake = Handshake.None;
            serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        }
 
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            this.Invoke(new EventHandler(delegate
            {
                // 更新UI
                textBoxReceive.AppendText(indata);
            }));
        }
 
        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.WriteLine(textBoxSend.Text);
            }
            else
            {
                MessageBox.Show("Port is not open!");
            }
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                comboBoxPort.Items.Add(s);
            }
            comboBoxPort.SelectedIndex = comboBoxPort.Items.Count > 0 ? 0 : -1;
        }
 
        private void buttonOpenPort_Click(object sender, EventArgs e)
        {
            if (comboBoxPort.SelectedIndex >= 0)
            {
                serialPort.PortName = comboBoxPort.SelectedItem.ToString();
                serialPort.Open();
                buttonOpenPort.Enabled = false;
                comboBoxPort.Enabled = false;
            }
        }
 
        private void buttonClosePort_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
                buttonOpenPort.Enabled = true;
                comboBoxPort.Enabled = true;
            }
        }
    }
}