C#窗体程序,创建多个串口的接收和发送的完整代码
时间: 2024-09-14 07:10:07 浏览: 46
C#串口介绍以及简单串口通信程序设计和实现
在C#中创建一个窗体程序处理多个串口的接收和发送,你需要做的是首先安装`System.IO.Ports`命名空间来访问串口功能,然后编写一个包含多个串口实例的类,并在窗体上添加控件来管理每个串口的状态。下面是一个简化的示例代码:
```csharp
using System;
using System.IO.Ports;
using System.Threading;
public partial class MainForm : Form
{
private SerialPort[] serialPorts = new SerialPort[2]; // 假设最多有两个串口
public MainForm()
{
InitializeComponent();
// 初始化串口设置
for (int i = 0; i < serialPorts.Length; i++)
{
serialPorts[i] = new SerialPort();
serialPorts[i].Name = $"SerialPort_{i + 1}";
serialPorts[i].DataReceived += SerialPort_DataReceived; // 注册数据接收事件
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
foreach (SerialPort port in serialPorts)
{
if (!port.IsOpen) // 如果串口未打开
{
try
{
port.Open(); // 尝试打开串口
btnConnect.Enabled = false; // 防止多次连接
Console.WriteLine($"Connected to {port.Name}");
}
catch (Exception ex)
{
MessageBox.Show($"Failed to open {port.Name}: {ex.Message}");
}
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string data = txtMessage.Text;
if (selectedPort.SelectedIndex != -1) // 确保选择了串口
{
SerialPort selectedPort = serialPorts[selectedPort.SelectedIndex];
if (selectedPort.IsOpen)
{
selectedPort.Write(data);
Console.WriteLine($"Sent message to {selectedPort.Name}: {data}");
}
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] buffer = new byte[port.BytesToRead];
port.Read(buffer, 0, buffer.Length);
textBoxSerialOutput.AppendText($"{DateTime.Now.ToString("HH:mm:ss")} - {port.Name}: {BitConverter.ToString(buffer)}\n");
}
}
阅读全文