<Window x:Class="SerialPortExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SerialPort Example" Height="200" Width="300">
<StackPanel Margin="10">
<ComboBox x:Name="cbxPortName" Width="120"/>
<TextBox x:Name="tbxDataToSend" Margin="0 10" Width="200"/>
<StackPanel Orientation="Horizontal" Margin="0 10">
<Button x:Name="btnOpenPort" Content="Open" Click="btnOpenPort_Click" Width="80" Margin="0 0 10 0"/>
<Button x:Name="btnSendData" Content="Send" Click="btnSendData_Click" Width="80"/>
</StackPanel>
<TextBox x:Name="tbxReceivedData" TextWrapping="Wrap" Text="TextBox" Width="120"/>
</StackPanel>
</Window>
上面是UI界面设计代码
2、后台代码:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Windows;
namespace SerialPortExample
{
public partial class MainWindow : Window
{
private SerialPort serialPort;
public MainWindow()
{
InitializeComponent();
//读取电脑的串口,并且将串口数据添加到下拉菜单中
string[] portNames = SerialPort.GetPortNames();
cbxPortName.ItemsSource = portNames;
cbxPortName.SelectedIndex = 0;
serialPort = null;
}
private void btnOpenPort_Click(object sender, RoutedEventArgs e)
{
try
{
if (serialPort == null)
{
// Create serial port object
serialPort = new SerialPort(cbxPortName.SelectedValue.ToString(), 9600);
serialPort.DataReceived += SerialPort_DataReceived;
}
if (!serialPort.IsOpen)
{
serialPort.Open();
// Disable port selection
cbxPortName.IsEnabled = false;
// Update UI
btnOpenPort.Content = "Close";
}
else
{
// Close serial port
serialPort.Close();
serialPort = null; //如果串口是打开的,将其关闭,重要的是:将串口设置为空,以便于创建一个新的接口实例
// Enable port selection
cbxPortName.IsEnabled = true;
// Update UI
btnOpenPort.Content = "Open";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void btnSendData_Click(object sender, RoutedEventArgs e)
{
try
{
if (serialPort != null && serialPort.IsOpen)
{
// Send data
serialPort.Write(tbxDataToSend.Text);
MessageBox.Show("Data sent!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
// Read available bytes from the serial port
// 这行代码是创建了一个 byte 数组 buffer,用来存储从串口读取的数据。
//serialPort.BytesToRead:返回当前串口缓冲区中可供读取的字节数
//创建了一个与缓冲区大小相同的字节数组buffer,以确保可以完整地读取到所有数据。
byte[] buffer = new byte[serialPort.BytesToRead];
//使用 SerialPort 对象从串口读取数据,并将读取的数据存储在一个字节数组中。
//其中,buffer 是要存储数据的字节数组,0 是数据存储的起始位置,buffer.Length 是要读取的字节数。
serialPort.Read(buffer, 0, buffer.Length);
//将字节数组buffer中的数据解码为字符串,使用的编码格式是当前系统的默认编码格式
string data = Encoding.Default.GetString(buffer);
// Update the UI with received data
Dispatcher.Invoke(() =>
{
tbxReceivedData.Text += data;
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}