使用c#开发串口接收工具

vs2022 c#学习:

1.使用c#开发串口接收工具:

绘制界面:
使用c#开发串口接收工具_第1张图片

添加串口组件:
使用c#开发串口接收工具_第2张图片

使用c#开发串口接收工具_第3张图片

在form1里边添加串口接收相关的:

        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            serialPort1.Encoding = Encoding.GetEncoding("GB2312");
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

        }
        //串口接收
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string rec_data;
                rec_data = serialPort1.ReadExisting();
                textBox1.AppendText(rec_data);
                textBox1.AppendText("\r\n");
            }
            catch { }


        }

按键扫描函数:

        private void button1_Click(object sender, EventArgs e)
        {
            SearchAddserialtocombox(serialPort1, comboBox1);
        }
        private void SearchAddserialtocombox(SerialPort Myport, ComboBox mybox)
        {

            string[] port_num = new string[20];
            string Midstring1;
            mybox.Items.Clear();
            for(int i = 1; i < 20;i++)
            {
                try
                {
                    Midstring1 = "COM" + i.ToString();
                    Myport.PortName = Midstring1;
                    Myport.Open();
                    port_num[i - 1] = Midstring1;
                    Myport.Close();
                    mybox.Text = port_num[i - 1];
![在这里插入图片描述](https://img-blog.csdnimg.cn/72ce24eff571412d9047ca08c22701dd.png#pic_center)

                }
                catch { };

            }

        }

打开串口

        private void button2_Click(object sender, EventArgs e)
        {
            if(button2.Text == "打开串口")
            {
                try
                {
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    serialPort1.Open();
                    button2.Text = "关闭串口";
                }
                catch
                {
                    MessageBox.Show("串口打开错误");
                }

            }
            else{
                try
                {
                    serialPort1.Close();
                    button2.Text = "打开串口";

                }
                catch
                {

                }
            }
        }

清空接收:

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

接收:

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

你可能感兴趣的:(c#,开发语言)