Пример #1
0
        private void button_OpenSerial_Click(object sender, EventArgs e)
        {
            if (comboBox_AvailableCom.SelectedValue == null)//先判断是否有可用串口
            {
                MessageBox.Show("无可用串口,无法打开!", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;//没有串口,提示后直接返回
            }

            if (helper.ComPortIsOpen == false)
            {
                try                                                                   //尝试打开串口
                {
                    var portName = comboBox_AvailableCom.SelectedValue.ToString();    //设置要打开的串口
                    var baudRate = Convert.ToInt32(comboBox_Rate.SelectedValue);      //设置当前波特率
                    var parity   = Convert.ToInt32(comboBox_ParityCom.SelectedValue); //设置当前校验位
                    var dataBits = Convert.ToInt32(comboBox_DataBits.SelectedValue);  //设置当前数据位
                    var stopBits = Convert.ToDouble(comboBox_StopBits.SelectedValue); //设置当前停止位
                    helper.Open(portName, baudRate, parity, dataBits, stopBits);
                }
                catch//如果串口被其他占用,则无法打开
                {
                    MessageBox.Show("无法打开串口,请检测此串口是否有效或被其他占用!", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    helper.GetPorts(); //刷新当前可用串口
                    return;            //无法打开串口,提示后直接返回
                }

                //↓↓↓↓↓↓↓↓↓成功打开串口后的设置↓↓↓↓↓↓↓↓↓
                button_OpenSerial.Enabled         = false;
                button_CloseSerial.Enabled        = true;
                button_StartOrStopReceive.Enabled = true;
                button_Reset.Enabled          = false; //打开串口后失能重置功能
                comboBox_AvailableCom.Enabled = false; //失能可用串口控件
                comboBox_Rate.Enabled         = false; //失能可用波特率控件
                comboBox_ParityCom.Enabled    = false; //失能可用校验位控件
                comboBox_DataBits.Enabled     = false; //失能可用数据位控件
                comboBox_StopBits.Enabled     = false; //失能可用停止位控件
                //↑↑↑↑↑↑↑↑↑成功打开串口后的设置↑↑↑↑↑↑↑↑↑
            }
        }