C# winform 串列埠通訊時檢測電腦可用串列埠並顯示
阿新 • • 發佈:2019-02-19
單擊同一個按鈕實現顯示“全部串列埠”和“可用串列埠”想切換
#region 全部串列埠和可用串列埠切換 private void button1_Click(object sender, EventArgs e) { switch (button1.Text) { case "可用串列埠": try { button1.Text = "全部串列埠"; cb_port.Items.Clear(); string[] str = SerialPort.GetPortNames(); for (int i = 0; i < str.Length; i++) { cb_port.Items.Add(str[i]); } cb_port.SelectedIndex = 0; } catch (Exception) { MessageBox.Show("沒有可用埠","提示"); } break; case "全部串列埠": button1.Text = "可用串列埠"; cb_port.Items.Clear(); for (int i = 1; i <= 16; i++) { cb_port.Items.Add("COM"+i); } cb_port.SelectedIndex = 0; break; default: MessageBox.Show("請選擇可用串列埠"); break; } } #endregion
本程式碼段中cb_port是comboBox控制元件