private void cbCom_SelectedIndexChanged(object sender, EventArgs e) { string name = cbCom.Text; if (name == "" || cfg.select_serial_port == name) { return; } string portName = SerialPortTool.GetSerialPortByName(name); if (portName == null) { showRedTip("无效端口"); return; } }
private void init_Serial_List() { List <string> sl = SerialPortTool.GetSerialPortList(); if (sl == null) { showRedTip("读取串口列表失败"); return; } for (int i = 0; i < sl.Count; i++) { string com = sl[i]; if (cbCom.Items.IndexOf(com) == -1) { cbCom.Items.Add(com); if (cfg.select_serial_port == com) { cbCom.SelectedItem = com; } } } for (int i = cbCom.Items.Count - 1; i >= 0; i--) { string com = cbCom.Items[i].ToString(); if (sl.IndexOf(com) == -1) { if (cbCom.SelectedIndex == i) { cbCom.Enabled = true; btnStartSerial.ImageIndex = 0; toolTip1.SetToolTip(btnStartSerial, "打开串口"); showRedTip("串口被移除"); } cbCom.Items.RemoveAt(i); } } }
//通过WMI获取COM端口 public static List <string> GetSerialPortList() { return(SerialPortTool.MulGetHardwareInfo(HardwareEnum.Win32_SerialPort, "Name")); }
private bool open_Serial() { if (serialPort.IsOpen) { return(true); } int baud; if (!int.TryParse(cbBits.Text, out baud)) { return(false); } try { serialPort.PortName = SerialPortTool.GetSerialPortByName(cbCom.Text); serialPort.BaudRate = baud; serialPort.Open(); } catch (System.IO.IOException ioe) { showRedTip(ioe.Message); } catch (System.UnauthorizedAccessException ioe) { showRedTip(ioe.Message); return(false); } catch (System.Exception e) { showRedTip(e.Message); return(false); } if (!serialPort.IsOpen) { showRedTip(serialPort.PortName + ": 打开串口失败"); return(false); } btnStartSerial.ImageIndex = 1; cbCom.Enabled = false; toolTip1.SetToolTip(btnStartSerial, "关闭串口"); showSuccessTip(serialPort.PortName + ": 打开成功, 速率: " + baud); int index = cfg.serial_baud_rate.IndexOf(baud.ToString()); if (index == -1 || baud != cfg.select_baud_rate || cbCom.Text != cfg.select_serial_port) { if (index == -1) { //添加新的速率到列表 for (int i = cfg.serial_baud_rate.Count - 1; i >= 0; i--) { int br = 0; if (int.TryParse(cfg.serial_baud_rate[i], out br)) { if (br == baud) //事实上不可能,因为前面 index = -1 { break; } if (baud > br) { cfg.serial_baud_rate.Insert(i + 1, baud.ToString()); cbBits.Items.Insert(i + 1, baud.ToString()); break; } if (i == 0) { cfg.serial_baud_rate.Insert(0, baud.ToString()); cbBits.Items.Insert(0, baud.ToString()); } } else { cfg.serial_baud_rate.RemoveAt(i); cbBits.Items.RemoveAt(i); } } } cfg.select_baud_rate = baud; cfg.select_serial_port = cbCom.Text; cfg.Save(); } recvInfoBox.Text = "接收: 0 字节"; sendInfoBox.Text = "发送: 0 字节"; return(true); }