本文详细解析了使用C#进行串口通信的方法,涵盖如何初始化和管理串行端口,以及实现高效的数据传输策略。
当然可以,以下是去掉不必要的部分后的代码:
```csharp
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SerialPort port1 = new SerialPort();
string InputData = String.Empty;
delegate void SetTextCallback(string text);
private void Port_Select()
{
// 获取机器中的串口地址
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void Form1_Load_1(object sender, EventArgs e)
{
Port_Select();
this.comboBox1.SelectedIndex = 0;
this.comboBox2.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == 关闭串口) // 当要关闭串口的时候
{
port1.DiscardOutBuffer();
port1.DiscardInBuffer();
port1.Close();
button1.Text = 打开串口;
label3.Text = 串口当前状况:未打开;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
}
else if (button1.Text == 打开串口) // 当要打开串口的时候
{
try
{
port1.PortName = comboBox1.SelectedItem.ToString();
port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem);
port1.DataBits = 8;
port1.RtsEnable = true;
port1.Open();
port1.DiscardOutBuffer();
port1.DiscardInBuffer();
button1.Text = 关闭串口;
comboBox1.Enabled = false;
comboBox2.Enabled = false;
label3.Text = $串口:{comboBox1.SelectedItem} 波特率:{comboBox2.SelectedItem} 数据位:8;
}
catch
{
button1.Text = 打开串口;
label3.Text = $串口:{comboBox1.SelectedItem.ToString()} 打开失败;
MessageBox.Show(该串口无法打开);
}
}
}
}
```