写在前面
C#中SerialPort类中没有直接可以判断串口连接状态的方法,在程序运行过程中需要能够实时检测串口的连接状态防止意外断开引起的异常。
以下的方法通过创建多线程进行轮询,通过SerialPort.GetPortNames();这个静态方法不停地获取设备串口号并与创建连接时记录的串口号进行比较。
后台代码
Thread thCheckSerialState= new Thread(new ThreadStart(delegate
{
while (true)
{
button_Port.Dispatcher.Invoke(new Action(delegate
{
string[] gCOM = System.IO.Ports.SerialPort.GetPortNames(); // 获取设备的所有可用串口
int j = gCOM.Length; // 得到所有可用串口数目
for (int i = 0; i < j; i++)
{
if (gCOM[i] == portName)
{
button_Port.Content = "关闭串口";
return;
}
}
button_Port.Content = "打开串口";
}), null);
Thread.CurrentThread.Join(500);//设定时间500ms
}
}));
thCheckSerialState.Start();//启动线程
前台代码
<ComboBox x:Name="comboBox_PortNumber" HorizontalAlignment="Left" Margin="76,3,0,0" VerticalAlignment="Top" Width="76" DropDownOpened="comboBox_PortNumber_DropDownOpened" Height="24" FontSize="12" />
<Button x:Name="button_Port" Content="打开串口" HorizontalAlignment="Left" Margin="0,119,-0.4,0" VerticalAlignment="Top" Width="162" Height="27" Click="button_Port_Click"/>
下载
基于上述开发的串口程序
下载链接:https://pan.baidu.com/s/1GjMK5oIuUbuCrIBfkX0noQ
提取码:qw7f
或访问
https://download.csdn.net/download/qq_44348665/12254541