public bool IsPortOpen()
{
//create vars for testing
bool _available = false;
SerialPort _tempPort;
String[] Portname = SerialPort.GetPortNames();
//create a loop for each string in SerialPort.GetPortNames
foreach (string str in Portname)
{
try
{
_tempPort = new SerialPort(str);
_tempPort.Open();
//if the port exist and we can open it
if (_tempPort.IsOpen)
{
comboBox1.Items.Add(str);
_tempPort.Close();
_available = true;
}
}
//else we have no ports or can't open them display the
//precise error of why we either don't have ports or can't open them
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
_available = false;
}
}
//return the temp bool
return _available;
}
c#验证串口可用性
最新推荐文章于 2024-05-30 16:33:26 发布