【问题标题】:C# - Detecting device on serial port hangs if no device existsC# - 如果不存在设备,则在串行端口上检测设备挂起
【发布时间】:2017-08-05 12:49:30
【问题描述】:

所以,我正在构建一个应用程序,该应用程序必须在继续之前检测设备是否连接到随机串行端口。虽然设备通过 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 说它没有显示的地步。

【问题讨论】:

  • 我认为您的代码中存在逻辑错误。为什么在foreach 中显示“无法检测到任何 Arduino 设备”?例如,您可能有很多 COM 端口,而您的 Arduino 板没有连接到第一个。
  • 我虽然是这样,但我应该如何在外面展示呢?如果我把它放在foreach 之外,即使设备连接,messagebox 也会显示。
  • 您可以使用标志变量。查看exampe
  • 请将其写为答案,以便我接受,这将代码修复。非常感谢 Aleks!
  • 我不确定我的建议是否能解决你所有的问题(我把我的 Arduino 给了朋友,所以我现在无法测试你的代码)

标签: c# serial-port usb


【解决方案1】:

在显示“未检测到 any 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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    相关资源
    最近更新 更多