C# 使用串口编程例子
使用C#调用com控件来与ESP32通信 打发用的IDE是:SharpDevelop 5.1
/* * 由SharpDevelop创建。 * 用户: xk100 * 日期: 2023/4/7 * 时间: 11:04 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO.Ports; namespace w1 { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { delegate void addstr(string text); public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); comboBox1.Items.Clear(); string [] comlist = SerialPort.GetPortNames(); foreach(string port in comlist){ comboBox1.Items.Add(port); } if(comlist.Length>0){ comboBox1.SelectedIndex=0; } // // TODO: Add constructor code after the InitializeComponent() call. // } void Button1Click(object sender, EventArgs e) { serialPort1.PortName=comboBox1.Text; serialPort1.Open(); serialPort1.BaudRate=int.Parse(comboBox3.Text); toolStripStatusLabel2.Text="串口"+serialPort1.PortName+"已打开,波特率:"+serialPort1.BaudRate.ToString(); button1.Enabled=false; button2.Enabled=true; } void MainFormLoad(object sender, EventArgs e) { } void ComboBox1SelectedIndexChanged(object sender, EventArgs e) { } void ComboBox1DropDown(object sender, EventArgs e) { comboBox1.Items.Clear(); string [] comlist = SerialPort.GetPortNames(); foreach(string port in comlist){ comboBox1.Items.Add(port); } } void Button2Click(object sender, EventArgs e) { serialPort1.Close(); toolStripStatusLabel2.Text=serialPort1.PortName+"串口已关闭"; button1.Enabled=true; button2.Enabled=false; } void Button3Click(object sender, EventArgs e) { if(serialPort1.IsOpen){ serialPort1.Write(comboBox2.Text+"\r\n"); comboBox2.Items.Add(comboBox2.Text); comboBox2.Text=""; }else{ MessageBox.Show("串口未打开","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); } } void SerialPort1DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); this.addtext(indata); } void addtext(string text){ if(this.textBox1.InvokeRequired){ addstr d=new addstr(addtext); this.textBox1.Invoke(d,new object[]{text}); }else{ this.textBox1.Text+=text+"\r\n"; this.textBox1.SelectionStart = this.textBox1.Text.Length; this.textBox1.ScrollToCaret(); } } void ListBox1SelectedIndexChanged(object sender, EventArgs e) { string cmd=listBox1.Items[listBox1.SelectedIndex].ToString(); if(serialPort1.IsOpen){ serialPort1.Write(cmd+"\r\n"); }else{ MessageBox.Show("串口未打开","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); } } } }
完整的代码下载: