如:(项目代码摘录)
private void ReceivedData(string line) { m_ReceivedTextList.Items.Insert(0, string.Format( "[{0}]\t{1} ===> {2}", DateTime.Now.ToShortTimeString(), m_commandComboBox.Text.Trim(), line ) ); } void OnSerialPort_DataReceived(object sender, StringEventArgs e) { if (this.InvokeRequired) {//这里不能用Invoke this.BeginInvoke((MethodInvoker)delegate { ReceivedData(e.Message); }); } else { ReceivedData(e.Message); } m_lastReceivedLine = e.Message; m_autoResetEvent.Set(); } private bool IdentifyDevice(string id, string portName) { if (!m_serialPortHelper.IsOpened) { Parameter.PortName = portName; m_serialPortHelper.SetParameter(Parameter); m_serialPortHelper.OpenPort(); } m_serialPortHelper.Send("*IDN?"); var timeout = ! m_autoResetEvent.WaitOne(1000); //ClosePort(); if (timeout) { return false; } else { return m_lastReceivedLine.StartsWith(id); } } private void OnAutoFindPortButton_Click(object sender, EventArgs e) { var oldPort = Parameter.PortName; bool foundPort = false; this.Enabled = false; if (!string.IsNullOrEmpty(DeviceID)) { if (!IdentifyDevice(DeviceID, Parameter.PortName)) { //ClosePort(); int i = m_allPortsComboBox.Items.Count - 1; for (; i >= 0 ; i--) { if (m_allPortsComboBox.Items[i].ToString() != oldPort) { m_allPortsComboBox.SelectedIndex = i; if (IdentifyDevice(DeviceID, m_allPortsComboBox.Text)) { break; } //ClosePort(); } } foundPort = i >= 0; } else { foundPort = true; } if (foundPort) { MessageBox.Show(string.Format("Find port with specified device ID: {0}", DeviceID)); } else { MessageBox.Show(string.Format("Can not find port with specified device ID: {0}", DeviceID)); m_allPortsComboBox.SelectedItem = oldPort; } this.Enabled = true; } else { MessageBox.Show("Can not find port without device ID."); } }