public static bool Connect(string strCom, int nBaudrate) { SerialPortUtil serialPort; try { string[] coms = SerialPortUtil.GetComList(); if (!coms.Contains(strCom)) { string str = string.Format("未找到串口:{0}", strCom); PrintLog.LogText(string.Format(str)); #if TEST OutputDebugString(str); #endif return(false); } if (dictionarySerialPort.ContainsKey(strCom)) { serialPort = dictionarySerialPort[strCom]; } else { serialPort = new SerialPortUtil(strCom, nBaudrate.ToString(), "0", "8", "1"); dictionarySerialPort.Add(strCom, serialPort); } serialPort.OpenPort(); } catch { return(false); } if (serialPort.IsOpen) { return(true); } else { return(false); } }
/// <summary> /// 初始化串口 /// </summary> private static bool InitSerialPort(string strCom, out SerialPortUtil serialPort, int nBaudrate) { if (dictionarySerialPort.ContainsKey(strCom)) //是否存在串口 { serialPort = dictionarySerialPort[strCom]; } else { serialPort = new SerialPortUtil(strCom, nBaudrate.ToString(), "0", "8", "1"); dictionarySerialPort.Add(strCom, serialPort); } if (serialPort == null) { return(false); } return(true); }