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