C#编写简易的上位机

标题C#编写简易的上位机

C#编写简易的上位机_第1张图片
代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace chuankou1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
   

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 1; i < 20; i++)
            {
                comboBox1.Items.Add("COM" + i.ToString());
            }
            comboBox1.Text = "COM1";//串口号默认值
            comboBox2.Text = "4800";//波特率默认值

            //很重要
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);//必须手动添加
        }
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)//串口数据接收事件
        {
            if (!radioButton3.Checked)//如果接收模式为字符模式
            {
                string str = serialPort1.ReadExisting();//字符串方式读
                textBox2.AppendText(str);//添加内容
            }
            else//如果接收模式为数值模式
            {
                byte data;
                data = (byte)serialPort1.ReadByte();//此处需要强制类型转换,将int类型数据转换为byte
                string str = Convert.ToString(data, 16).ToUpper();//转换为大写十六进制字符串
                textBox2.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//空位补"0"
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox1.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//十进制数据转换
                serialPort1.Open();
                button1.Enabled = false;//打开串口按钮不可用
                button2.Enabled = true;//关闭串口
            }
            catch 
            {
                MessageBox.Show("端口错误,请检查串口", "错误");
                
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();//关闭串口
                button1.Enabled = true;//打开串口按钮可用
                button2.Enabled = false;//关闭串口按钮不可用
            }
            catch (Exception err)
            {

                throw;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] Data = new byte[1];//只存储一个字节
            if (serialPort1.IsOpen)//判断串口是否打开,如果打开就执行下一步操作
            {
                if (textBox2.Text!=" ")
                {
                    if (!radioButton1.Checked)//如果是字符模式
                    {
                        try
                        {
                            serialPort1.WriteLine(textBox2.Text);//写数据
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show("窗口数据写入错误", "错误");//出错提示
                            serialPort1.Close();
                            button1.Enabled = true;//打开串口按钮可用
                            button2.Enabled = false;//关闭串口按钮不可用
                            
                        }
                    }
                    else
                    {
                        for (int i = 0; i < (textBox2.Text.Length - textBox2.Text.Length % 2) / 2; i++)
                        {
                            Data[0] = Convert.ToByte(textBox2.Text.Substring(i * 2, 2), 16);
                            serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
                        }
                        if (textBox2.Text.Length % 2 != 0)//剩下一位单独处理
                        {
                            //Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - textBox2.Text.Length % 2, textBox2.Text.Length % 2), 16);
                            Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - 1,1), 16);
                            serialPort1.Write(Data, 0, 1);//发送
                        }
                    }
                }
            }
        }

        //private void textBox1_TextChanged(object sender, EventArgs e)
        //{
        //    textBox1.ScrollToCaret();//将滚动条调至最下
        //}
    }
}

C#编写简易的上位机_第2张图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace chuankuo2
{
    public partial class Form1 : Form
    {
        //定义一些常量
        const byte DeviceOpen1 = 0x01;
        const byte DeviceClose1 = 0x81;

        const byte DeviceOpen2 = 0x02;
        const byte DeviceClose2 = 0x82;

        const byte DeviceOpen3 = 0x03;
        const byte DeviceClose3 = 0x83;

        byte[] SerialPortDataBuffer = new byte[1];
        public Form1()
        {           
            InitializeComponent();//窗口构造
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)//如果串口是打开
            {
                try
                {
                    serialPort1.Close();//关闭串口
                }
                catch 
                {                 
                }
                button1.Text = "打开串口";//显示打开串口
            }
            else//如果串口关闭
            {
                try
                {
                    serialPort1.PortName = comboBox1.Text;//端口号
                    serialPort1.Open();//打开端口
                    button1.Text = "关闭串口";
                }
                catch 
                {
                    MessageBox.Show("串口打开失败", "错误");
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)//点击屏幕空白处
        {
            SearchAndAddSerialToComboBox(serialPort1, comboBox1);//调用扫描函数
        }
        private void SearchAndAddSerialToComboBox(SerialPort MyPort,ComboBox MyBox)//定义扫描函数
        {                                           //将可用端口号添加到ComboBox
            //string[] MyString = new string[20];//定义20个string类型的数组
            string Buffer; //缓存
            MyBox.Items.Clear();//清空ComboBox内容
            //int count = 0;
            for (int i = 1; i < 20; i++)//循环
            {
                try
                {
                    Buffer = "COM" + i.ToString();
                    MyPort.PortName = Buffer;
                    MyPort.Open();
                    //MyString[i - 1] = Buffer;
                    //MyString[count] = Buffer;
                    MyBox.Items.Add(Buffer);
                    MyPort.Close();
                    //count++;
                }
                catch 
                {
                    //count--;
                }
            }
            //MyBox.Text = MyString[0];//初始化
        }
        private void WriteByteToSerialPort(byte data)//单字节写入串口
        {
            byte[] Buffer = new byte[2] { 0x00, data };//定义数组
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Write(Buffer, 0, 2);//写数据
                }
                catch 
                {
                    MessageBox.Show("串口数据发送出错,请检查", "错误");
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceOpen1);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceClose1);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceOpen2);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceClose2);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceOpen3);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            WriteByteToSerialPort(DeviceClose3);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SearchAndAddSerialToComboBox(serialPort1, comboBox1);//扫描功能的实现
        }
    }
}

欢迎关注我!
C#编写简易的上位机_第3张图片

你可能感兴趣的:(上位机,c#)