C# 获得串口名添加到列表框





C# 获得串口名添加到列表框_第1张图片

        public Form1()
        {
            InitializeComponent(); 
  
            //portsArray数组获得所有串口列表
            string[] portsArray = SerialPort.GetPortNames(); 

            //把获得的串口名添加到列表框
            foreach (string portnumber in portsArray)
            {
                comboBox_Com.Items.Add(portnumber);
            }          
        }

        private void button_Open_Click(object sender, EventArgs e)//打开串口按钮
        {
            if (!mySP.IsOpen)
            {
                mySP.PortName = comboBox_Com.SelectedItem.ToString();//串口名
                mySP.BaudRate = (int)19200;
                mySP.DataBits = (int)8;
                mySP.Parity = Parity.None;
                mySP.StopBits = StopBits.One;
                mySP.Open();
                button_Open.Text = "close";//按钮显示关闭

            }
            else
            {
                mySP.Close();
                //MessageBox.Show("Err:Open Comm Port");
                button_Open.Text = "open";
            }  
        }


你可能感兴趣的:(C#,学习)