2017-08-05 45 views
1

因此,我正在構建一個應用程序,它必須在繼續之前檢測設備是否連接到隨機串行端口。雖然設備通過USB連接,但它被列爲COMPORT(在我的情況下爲COM5,但取決於PC)。我有下面的代碼,如果該設備插入工作,沒問題,只需一秒鐘就可以正常工作,但如果與我正在查找的名稱匹配的設備沒有連接,應用程序什麼也不做,當它應該顯示提起messagebox說沒有設備連接。幫助將不勝感激。C# - 如果沒有設備存在,串口檢測設備掛起

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說沒有顯示的點。

+0

我認爲你的代碼中有一個邏輯錯誤。 'foreach'裏面爲什麼會顯示「無法檢測到任何Arduino設備」?例如,你可能有很多COM端口,而你的Arduino板沒有連接到第一個端口。 –

+0

我雖然這樣,但我應該如何顯示外部?如果我將它放在'foreach'之外,即使設備連接,'messagebox'也會顯示。 – szoszu

+0

您可以使用標誌變量。看一個[例如](https://pastebin.com/kEp6T5Va) –

回答

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