基本信息
源码名称:C# RS232串口通信
源码大小:0.20M
文件格式:.rar
开发语言:C#
更新时间:2020-08-17
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍
串口通信测试程序,包含一个串口参数设置窗口


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

namespace RS232Comm
{
    public partial class MainForm : Form
    {
        protected Boolean stop = false;    
        protected Boolean conState = false;
        private StreamReader sRead;
        public MainForm()
        {
            InitializeComponent();
        }
        string strRecieve;
        bool bAccept = false;
        SerialPort sp = new SerialPort();
 
        public static string strPortName = "";
        public static string strBaudRate = "";
        public static string strDataBits = "";
        public static string strStopBits = "";

        private void btnSetSP_Click(object sender, EventArgs e)//串口设置
        {
            timer1.Enabled = false;
            sp.Close();
            ComSet dlg = new ComSet();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                sp.PortName = strPortName;
                sp.BaudRate = int.Parse(strBaudRate);
                sp.DataBits = int.Parse(strDataBits);
                sp.StopBits = (StopBits)int.Parse(strStopBits);
                sp.ReadTimeout = 500;
            }
        }

        private void btnSwitchSP_Click(object sender, EventArgs e)//打开串口
        {
            if (btnSwitchSP.Text == "打开串口")
            {
                if (strPortName != "" && strBaudRate != "" && strDataBits != "" && strStopBits != "")
                {
                    try
                    {
                        if (sp.IsOpen)
                        {
                            sp.Close();
                            sp.Open(); //打开串口    
                        }
                        else
                        {
                            sp.Open();//打开串口    
                        }
                        btnSwitchSP.Text = "关闭串口";
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = true;
                        this.toolStripStatusLabel1.Text = "端口号:"   sp.PortName   " 丨";
                        this.toolStripStatusLabel2.Text = "波特率:"   sp.BaudRate   " 丨";
                        this.toolStripStatusLabel3.Text = "数据位:"   sp.DataBits   " 丨";
                        this.toolStripStatusLabel4.Text = "停止位:"   sp.StopBits   " 丨";
                        this.toolStripStatusLabel5.Text = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("错误:"   ex.Message,"C#串口通信");
                    }
                }
                else
                {
                    MessageBox.Show("请先设置串口!","RS232串口通信");
                }
            }
            else
            {
                timer1.Enabled = false;
                btnSwitchSP.Text = "打开串口";
                sp.Close();
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                this.toolStripStatusLabel1.Text = "端口号:端口未打开丨";
                this.toolStripStatusLabel2.Text = "波特率:端口未打开丨";
                this.toolStripStatusLabel3.Text = "数据位:端口未打开丨";
                this.toolStripStatusLabel4.Text = "停止位:端口未打开丨";
                this.toolStripStatusLabel5.Text = "";
            }
        }

  
        private void btnSendData_Click(object sender, EventArgs e)//数据发送
        {
            if (sp.IsOpen)
            {
                try
                {
                    sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即信息交换用汉字编码字符集
                    sp.Write(txtSend.Text);
                }
                catch (Exception ex)//若应用程序出现调试问题
                {
                    MessageBox.Show("错误:"   ex.Message);
                }
            }
            else
            {
                MessageBox.Show("请先打开串口!");
            }
        }


        delegate void DelegateAcceptData();
        void fun()
        {
            while (bAccept )
            { AcceptData(); }
        }

        delegate void reaction();
        void AcceptData()
        {
            if (textBox2.InvokeRequired)
            {
                try
                {
                    DelegateAcceptData ddd = new DelegateAcceptData(AcceptData);
                    this.Invoke(ddd, new object[] { });
                }
                catch { }
            }
            else
            {
                try
                {
                    strRecieve = sp.ReadExisting();
                    textBox2.Text  = strRecieve;
                }
                catch (Exception e) { }
            }
        }
        
        private void btnReceiveData_Click(object sender, EventArgs e)//接受信息
        {
            sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即信息交换用汉字编码字符集
            if (sp.IsOpen)
            {
                timer2.Enabled = true;
            }
            else
            {
                MessageBox.Show("请先打开串口!");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {            
            string str1;
            str1 = sRead.ReadLine();
            if (str1 == null)
            {
                timer1.Stop();
                sRead.Close();
                MessageBox.Show("文件发送成功!","C#串口通信");
                this.toolStripStatusLabel5.Text = "";
                return;
            }
            byte[] data = Encoding.Default.GetBytes(str1);
            sp.Write(data, 0, data.Length);
            this.toolStripStatusLabel5.Text = "        文件发送中...";
        }

  
        private void btnOutputInfo_Click(object sender, EventArgs e)//导出信息
        {
            try
            {
                string path = @"c:\output.txt";
                string content = this.textBox2.Text;
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter write = new StreamWriter(fs);
                write.Write(content);
                write.Flush();
                write.Close();
                fs.Close();
                MessageBox.Show("接收信息导出在"   path);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void btnClearInfo_Click(object sender, EventArgs e)//清空接受区
        {
            this.textBox2.Text = "";
        }

        private void btnQueryFile_Click(object sender, EventArgs e)//设置文件路径
        {
            String filename;
            OpenFileDialog Open1 = new OpenFileDialog(); 
            Open1.FileName = "";
            Open1.ShowDialog();
            filename = Open1.FileName;

            if (filename == "")
            {
                MessageBox.Show("请选择要发送的文件!", "Error");
                return;
            }
            textBox1.Text = filename;

            if (filename != null)
            {
                StreamReader sRead = new StreamReader(filename);
            }
            btnReceiveData.Enabled = true;

        }

        private void btnSendFile_Click(object sender, EventArgs e)//文件发送
        {
            string fileName = textBox1.Text;

            if (fileName == "")
            {
                MessageBox.Show("请选择要发送的文件!", "Error");
                return;
            }
            else
            {
                sRead = new StreamReader(fileName);
            }
            timer1.Start();
        }
 
        private void timer2_Tick(object sender, EventArgs e)
        {
            string str = sp.ReadExisting();
            string str4 = str.Replace("\r", "\r\n");
            textBox2.AppendText(str4);
            textBox2.ScrollToCaret();
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            this.toolStripStatusLabel1.Text = "端口号:端口未打开丨";
            this.toolStripStatusLabel2.Text = "波特率:端口未打开丨";
            this.toolStripStatusLabel3.Text = "数据位:端口未打开丨";
            this.toolStripStatusLabel4.Text = "停止位:端口未打开丨";
            this.toolStripStatusLabel5.Text = "";
        }
    }
}