void AutoScan() { try { ComSerial.ReadTimeout = 100; //ComPortList = SerialPort.GetPortNames(); //foreach (string port in ComPortList) //{ // ComSerial.PortName = port.ToString(); //} ComSerial.PortName = SerialPort.GetPortNames().LastOrDefault(); //Comport = ComSerial.PortName; //GetRoomAssignment(ComSerial.PortName); ComSerial.BaudRate = 9600; ComSerial.DataBits = 8; ComSerial.Parity = Parity.None; ComSerial.StopBits = StopBits.One; ComSerial.Close(); ComSerial.Open(); ComSerial.DataReceived += new SerialDataReceivedEventHandler(ComSerial_DataReceived); } catch (Exception ex) { ComSerial.Close(); } }
private void button_CanCom_Click(object sender, EventArgs e) { ComboBox box = comboBox_CanCom; ComSerial com = my_can; if (box.Enabled) { if (box.SelectedIndex >= 0) { string name = box.SelectedItem.ToString(); com.Open(name); if (com.Is_Open()) { box.Enabled = false; return; } } MessageBox.Show("请选择COM", "Err", MessageBoxButtons.OK, MessageBoxIcon.Question); } else { com.Close(); box.Enabled = true; } }
void AutoScan() { try { ComPortList = SerialPort.GetPortNames(); foreach (string port in ComPortList) { ComSerial.PortName = port.ToString(); PortAvailable = port.ToString(); } ComSerial.PortName = txtComPort.Text; ComSerial.Open(); if (!string.IsNullOrWhiteSpace(txtBaundRate.Text)) { ComSerial.BaudRate = Convert.ToInt32(txtBaundRate.Text); } if (!string.IsNullOrWhiteSpace(cmbParity.Text)) { ComSerial.Parity = SystemProperties.Getparity(cmbParity.Text); } if (!string.IsNullOrWhiteSpace(cmbStopBits.Text)) { ComSerial.StopBits = SystemProperties.GetStopBit(cmbStopBits.Text); } if (!string.IsNullOrWhiteSpace(txtDataBits.Text)) { ComSerial.DataBits = Convert.ToInt32(txtDataBits.Text); } //txtStatus.Text = ""; ComSerial.DataReceived += new SerialDataReceivedEventHandler(ComSerial_DataReceived); //ComSerial.Close(); } catch (Exception ex) { //ComSerial.Close(); //ComSerial.ReadTimeout = 100; //ComSerial.PortName = PortAvailable; //ComSerial.Open(); //ComSerial.BaudRate = 9600; //ComSerial.Parity = Parity.None; //ComSerial.StopBits = StopBits.One; //ComSerial.DataBits = 8; //ComSerial.DataReceived += new SerialDataReceivedEventHandler(ComSerial_DataReceived); txtStatus.Text = "Available serial port: " + Environment.NewLine + PortAvailable + Environment.NewLine + Environment.NewLine + "Defaul settings:" + Environment.NewLine + " BoundRate: 9600, DataBits: 8,StopBits: One,Parity: None "; AutoScanTimer.Stop(); AutoScanTimer.Enabled = false; ComSerial.Close(); } }