本教程基于 win10 x64 位操作系统,软件环境为 Microsoft VisualStudio Community 2015(以下简称 VS) namespace SerialPort02
 namespace SerialPort02
{
    public partial class Form1 : Form
    {
        SerialPort SpCom = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
}
        private void 清除发送_Click(object sender, EventArgs e)
        {
            txtSend.Text = string.Empty;
        }
        private void Textbox_Load(object sender, EventArgs e)
        {
            SpCom.DataReceived = SpCom_DataReceived;
        }
        private void SpCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int length = SpCom.BytesToRead;
            byte[] recData = new byte[length];
            SpCom.Read(recData, 0, length);
            string recText = Encoding.GetEncoding("GB2312").GetString(recData);
            //更新接收区
            txtReceive.Invoke(new EventHandler(delegate
            {
                txtReceive.AppendText(recText);
            }));
        }
        private void btnClearRec_Click(object sender, EventArgs e)
        {
            txtReceive.Text = string.Empty;
        }
        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            if (SpCom.IsOpen)
            {
                SpCom.Close();
                btnOpenPort.Text = "打开串口";
            }
            else
            {
                InitPort();
                try
                {
                    SpCom.Open();
                    btnOpenPort.Text = "关闭串口";
                    MessageBox.Show("串口初始化成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }        

 
  
					
				
评论