//初始化端口函数 public Boolean initCOM() { String portName = "COM1"; if (ini.IniReadValue("设置", "portSelected") != "") { portName = ini.IniReadValue("设置", "portSelected"); } int baudRate = 9600; if (ini.IniReadValue("设置", "baudRate") != "") { baudRate = Int32.Parse(ini.IniReadValue("设置", "baudRate")); } int dataBits = 8; if (ini.IniReadValue("设置", "dataBits") != "") { dataBits = Int32.Parse(ini.IniReadValue("设置", "dataBits")); } StopBits oStopBits = StopBits.One; switch (ini.IniReadValue("设置", "stopBits")) { case "1": oStopBits = StopBits.One; break; case "1.5": oStopBits = StopBits.OnePointFive; break; case "2": oStopBits = StopBits.Two; break; default: oStopBits = StopBits.One; break; } //无奇偶校验位 Parity oParity = Parity.None; switch (ini.IniReadValue("设置", "parity")) { case "无": oParity = Parity.None; break; case "奇校验": oParity = Parity.Odd; break; case "偶校验": oParity = Parity.Even; break; default: oParity = Parity.None; break; } int ReadTimeout = 100; int WriteTimeout = -1; comHelp = new COMHelper(portName, baudRate, oParity, dataBits, oStopBits, ReadTimeout, WriteTimeout); if (!comHelp.IsOpen()) { if (!comHelp.Open()) { MessageBox.Show("端口打开失败", "提示"); //退出 return(false); } } else { MessageBox.Show("端口被占用", "提示"); //退出 return(false); } comHelp.AddReceiveEventHanlder(comHelp.serialPort_DataReceived);//将接收到数据,处理数据的方法注册进去 comHelp.ReceiveDataHandler += rds_ReceiveDataHandler; return(true); }