简体   繁体   中英

C# - Detecting device on serial port hangs if no device exists

So, I am building an app that has to detect whether a device is connected or not to a random serial port before continuing. Although the device connects via USB, it is listed as COMPORT (COM5 in my case, but it depends on the PC). I have the following code which does work if the device is plugged in, no problem, goes as normal in just one second, but if a device matching the name I am looking for is not connected, the application does nothing, when it should show up the messagebox saying no device is attached. Help would be appreciated.

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);
}

The above code runs in a separate backgroundworker component. As I said, if the device is connected, it does work, if the device is not, I never get to the point where the messagebox saying it is not shows.

You should complete foreach cycle before showing "Not detected any Arduino device". You may use flag variable for this. Please try this code:

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM