C# - 如果没有设备,检测串口上的设备会挂起

时间:2017-08-05 12:49:30

标签: c# serial-port usb

因此,我正在构建一个应用程序,在继续之前必须检测设备是否连接到随机串行端口。虽然设备通过USB连接,但它被列为COMPORT(在我的情况下是COM5,但它取决于PC)。我有以下代码,如果插入设备,没有问题,只需一秒钟就可以正常工作,但是如果与我正在寻找的名称匹配的设备没有连接,应用程序什么都不做,应该显示向上messagebox说没有附加设备。帮助将不胜感激。

ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
  foreach (ManagementObject item in searcher.Get())
  {
    string desc = item["Description"].ToString();
    string deviceId = item["DeviceID"].ToString();
    if (desc.Contains("Arduino"))
    {
      device_loc = deviceId;
      serializer.RunWorkerAsync();
      BeginInvoke((MethodInvoker)delegate
      {
         next_step.Enabled = true;
      });
    }
    else
    {
      MessageBox.Show("Could not detect any Arduino device connected, please connect your device.",
        "No device", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
      BeginInvoke((MethodInvoker)delegate
      {
          next_step.Text = "Ok, let's continue.";
          next_step.Enabled = true;
      });
    }
  }
}
catch (ManagementException xe)
{
  MessageBox.Show("Could not check for serial devices due to the following error: " + xe, 
    "Ooops", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

上述代码在单独的backgroundworker组件中运行。 正如我所说的,如果设备已连接,它确实有效,如果设备没有连接,我就永远不会到messagebox说它不显示的地步。

1 个答案:

答案 0 :(得分:0)

在显示“未检测到任何 Arduino设备”之前,您应该完成foreach周期。您可以使用标志变量。请尝试以下代码:

bool arduinoFound = false;
foreach (ManagementObject item in searcher.Get())
{
    string desc = item["Description"].ToString();
    if (desc.Contains("Arduino"))
    {
        arduinoFound = true;
    }
}

if (!arduinoFound)
    MessageBox.Show("Could not detect any Arduino device connected");