How to write a simple upper computer with C#

The interface of the upper computer is as follows

 It's a bit ugly, you can design it according to your own, here we focus on the realization of functions

Directly upload the code, open VS to create a new project, select Windows window application (NET. Framework) to create a good project

 Select the view, open the toolbox (shortcut Ctrl + Alt + x)

 In the toolbox, enter GroupBox, drag it into the interface, adjust the appropriate size, point the arrow to the frame of the GroupBox,

 Right-click to open the property interface, rewrite the text displayed on the interface in Text, and then change the font size in Font

 Open the toolbox again, enter ladel, drag 6 to the interface, and follow the above operations to change the Text to the corresponding name

 Open the toolbox, enter comboBox, drag and drop 5 to the interface, and correspond to each one in turn

 Enter serialPort in the toolbox, drag it over the interface, and the following interface will appear, which is used to obtain the information of the serial port

Double-click the blank space of the window, or right-click to enter the code interface

 Add the method text_Serial_port() to get the serial port of the computer, and then call the method in Form1_load,

 private void text_Serial_port()
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames(); //获得可用的串口
            for (int i = 0; i < ports.Length; i++)
            {
                comboBox1.Items.Add(ports[i]);
            }
            comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;//如果里面有数据,显示第0个
        }
private void Form1_Load(object sender, EventArgs e)
        {
            text_Serial_port();
        }

Run it and you will see the following interface. If the interface on the right appears, it means that there is no virtual serial port on the computer. You can query the virtual serial port and have related resources.

 After completing the above, go back to the interface, point the arrow to the comboBox of the stop position, right-click to open the properties, find ltems (collection), click (...) on the right to open the editor, and enter the following data in it (just copy, he will automatic sorting)

 

 stop bit:


1.5
2

Data bits:

8
7
6
5

 Baud rate:

1382400
921600
460800
256000
230400
128000
115200
76800
57600
43000
38400
19200
14400
9600
4800
1200

Parity:

None
Odd parity
Even parity

After all input, run the following screen

 Add the initialization method in the code, and then call the method in Form1_load, run the following results

            private void Form1_Load(object sender, EventArgs e)
        {
            text_Serial_port();
            Initialization();
        }

        //初始化
        private void Initialization()
        {
            comboBox2.Text = "1";
            comboBox3.Text = "8";
            comboBox4.Text = "115200";
            comboBox5.Text = "奇校验";

        }

 

 Open the toolbox, enter Button, find and drag it into the interface, adjust the size, and rewrite it in the Text in the property (open the serial port)

 

 Point the arrow to Button, double-click to enter the code interface, and add the Button method to it to open the serial port

 //串口的开关
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "打开串口")
            {
                try
                {
                    serialPort1.PortName = comboBox1.Text;//获取要打开的串口
                    serialPort1.BaudRate = int.Parse(comboBox4.Text);//获得波动率
                    serialPort1.DataBits = int.Parse(comboBox3.Text);//获得数据位
                    //设置停止位
                    if (comboBox2.Text == "1")
                    {
                        serialPort1.StopBits = StopBits.One;
                    }
                    else if (comboBox2.Text == "1.5")
                    {
                        serialPort1.StopBits = StopBits.OnePointFive;
                    }
                    else if (comboBox2.Text == "2")
                    {
                        serialPort1.StopBits = StopBits.Two;
                    }
                    //设置奇偶校验
                    if (comboBox5.Text == "无")
                    {
                        serialPort1.Parity = Parity.None;
                    }
                    else if (comboBox5.Text == "奇校验")
                    {
                        serialPort1.Parity = Parity.Odd;
                    }
                    else if (comboBox5.Text == "偶校验")
                    {
                        serialPort1.Parity = Parity.Even;
                    }
                    serialPort1.Open();//打开串口
                    button1.Text = "关闭串口";
                }
                catch (Exception err)
                {
                    MessageBox.Show("打开失败" + err.ToString(), "提示!");
                }
            }
            else
            {
                //关闭串口
                try
                {
                    
                        serialPort1.Close();//关闭串口

                }
                catch (Exception) { }
                button1.Text = "打开串口"; //按钮显示打开
            }
        }

 Enter TextBox in the toolbox, drag it to the interface, click the small arrow above the component, check MultiLine, and then adjust the size

 Open the properties of the TextBox, adjust the color of the screen in BackColor, adjust the color of the font in ForeColor, here I choose black for the interface, and blue for the font

 

 Point the mouse arrow to the serialPort and right-click to open the properties, click the lightning bolt on the property page, and find DataReceived below

 

 Double-click to enter the code interface and add the method of receiving information

//读取并显示接收的信息
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead; //获取可以读取的字节数

            byte[] buff = new byte[len];
            serialPort1.Read(buff, 0, len);//把数据读取到数组中
            string reslut = Encoding.Default.GetString(buff);
            //将byte值根据为ASCII值转为string
            Invoke((new Action(() =>
            {
                //还应该添加16制转化
                textBox1.AppendText(" " + reslut);     //追加显示在界面上        
            }
            )));

        }

Download a virtual assistant XCOM to test the effect, open the serial port one is COM1, the other is COM3, send data, and observe whether the data is displayed

Next, add clear data and hexadecimal display, find CheckBox in the toolbox, drag it to the interface, and change the Text to "hexadecimal display"

 Add the hexadecimal method in the code, and add the judgment in the if in serialPort1_DataReceived just now

 //16进制显示字符串
        private string byteToHexstr(byte[] buff)
        {
            string str = "";
            try
            {
                if (buff != null)
                {

                    for (int i = 0; i < buff.Length; i++)
                    {
                        //char a = (char)buff[i];
                        //str += a.ToString();
                        str += buff[i].ToString("x2");
                        str += " ";//两个之间用空格
                    }
                    //str = new string(buff);
                    return str;
                }
            }
            catch (Exception)
            {
                return str;
            }
            return str;
        }

 if judgment ceh

//读取并显示接收的信息
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead; //获取可以读取的字节数

            byte[] buff = new byte[len];
            serialPort1.Read(buff, 0, len);//把数据读取到数组中
            string reslut = Encoding.Default.GetString(buff);
            //将byte值根据为ASCII值转为string
            Invoke((new Action(() =>
            {
                if (checkBox1.Checked)//16进制转化
                {
                    textBox1.AppendText(" " + byteToHexstr(buff));
                }
                else
                {
                    textBox1.AppendText(" " + reslut);
                }
            }
            )));

        }

 Test: Check the hexadecimal transmission in the virtual serial port assistant, 01 02 03 04 05, and check the hexadecimal display in the host computer

After the display is successful, find the Button in the toolbox and drag it over the interface, change the Text to "clear data", double-click to add the method

//清除接收
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear(); 
        }   

 Add the ability to send messages

Find the TextBox from the toolbox and drag it to the interface, find the CheckBox and rename it to hexadecimal Send and add two Buttons and rename them "Send Information" and "Clear Data"

 Add 1 string conversion method of hexadecimal

        //字符串转16进制
        private byte[] strToHexbytes(string str)
        {
            str = str.Replace(" ", "");//清除空格
            byte[] buff;
            if ((str.Length % 2) != 0)
            {
                buff = new byte[(str.Length + 1) / 2];
                try
                {
                    for (int i = 0; i < buff.Length; i++)
                    {
                        buff[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                    }
                    buff[buff.Length - 1] = Convert.ToByte(str.Substring(str.Length - 1, 1).PadLeft(2, '0'), 16);
                    return buff;
                }
                catch (Exception err)
                {
                    MessageBox.Show("含有f非16进制的字符", "提示");
                    return null;
                }
            }
            else
            {
                buff = new byte[str.Length / 2];
                try
                {
                    for (int i = 0; i < buff.Length; i++)
                    {
                        buff[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                    }
                    //buff[buff.Length - 1] = Convert.ToByte(str.Substring(str.Length - 1, 1).PadLeft(2, '0'), 16);
                }
                catch (Exception err)
                {
                    {
                        MessageBox.Show("含有非16进制的字符", "提示");
                        return null;
                    }
                }
            }

            return buff;
        }

Add the method of sending information, and double-click Button3 to enter the code interface to add events


        private void button3_Click(object sender, EventArgs e)
        {
            
                Task.Run(() => {
                    send_();
                });
        }

        string data_;
        //发送数据  
        private void send_()
        {
            data_ = textBox2.Text.ToString();
                try
                {
                    if (data_.Length != 0)
                    {
                        data_ += " ";
                        if (checkBox2.Checked) //16进制发送
                        {
                            serialPort1.Write(Encoding.Default.GetString(strToHexbytes(data_)));
                        }
                        else
                        {
                            serialPort1.Write(data_);
                            //byte[] byteArray = Encoding.Default.GetBytes(shuju);//Str 转为 Byte值
                            //serialPort1.Write(byteArray, 0, byteArray.Length, 0, null, null); //发送数据         
                        }
                    }

                }
                catch (Exception) { }         
        }

Finally add the method to clear the data

        //清除数据
        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Clear();
        }

At this point, a simple host computer is ready, please point out any deficiencies.

Guess you like

Origin blog.csdn.net/weixin_73771688/article/details/130903050