標(biāo)題: c#寫的串口助手源碼 [打印本頁(yè)]

作者: laoxianccc    時(shí)間: 2018-6-14 20:51
標(biāo)題: c#寫的串口助手源碼
c#寫的串口助手的運(yùn)行界面:


全部源碼資料51hei下載地址:
4、COM_ok.zip (3.58 MB, 下載次數(shù): 116)


部分源碼預(yù)覽:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;

  9. using System.IO.Ports;
  10. using System.Threading;
  11. using System.Collections;
  12. using System.IO;

  13. namespace COM_A
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         public byte[] myBy;//傳遞串口接收到的數(shù)據(jù)
  18.         public int myByLenth = 0;//串口接收到的數(shù)據(jù)長(zhǎng)度
  19.         public string myStr;//串口接收的字符串
  20.         public bool receiveDtatFlag = false;
  21.         public int send_count = 0;

  22.         public Form1()
  23.         {
  24.             InitializeComponent();
  25.             //this.ControlBox = false;//最小化最大化關(guān)閉按鈕處理
  26.         }

  27.         private void Form1_Load(object sender, EventArgs e)//頁(yè)面加載
  28.         {
  29.             #region 串口設(shè)置初始化加載
  30.             try
  31.             {
  32.                 foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測(cè)
  33.                     comboBox1.Items.Add(com);
  34.                 //comboBox1.Text = (string)comboBox1.Items[0];//初始化選擇串口
  35.                 comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加載
  36.                 if (comboBox1.Text == "")
  37.                 {
  38.                     comboBox1.Text = (string)comboBox1.Items[0];//初始化選擇串口
  39.                 }

  40.             }
  41.             catch (Exception er)
  42.             {
  43.                 MessageBox.Show("端口加載失。" + er.Message, "提示");
  44.             }

  45.             //列出常用的波特率
  46.             string[] ss = new string[] { "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "57600", "115200" };
  47.             comboBox2.DataSource = ss;
  48.             /*for (int temp = 0; temp < 10; temp++)
  49.             {
  50.                 comboBox2.Items.Add(ss[temp]);
  51.             }*/
  52.             comboBox2.Text = myConfing.ConfingGetValue("buadRate");
  53.             if (comboBox2.Text == "")
  54.             {
  55.                 comboBox2.SelectedIndex = 3;
  56.             }
  57.             //comboBox2.SelectedIndex = 3;

  58.             //列出奇偶校驗(yàn)位
  59.             comboBox3.DataSource = Enum.GetNames(typeof(Parity));
  60.             //comboBox3.Items.Add("無(wú)校驗(yàn)");
  61.             //comboBox3.Items.Add("奇校驗(yàn)");
  62.             //comboBox3.Items.Add("偶校驗(yàn)");
  63.             //comboBox3.SelectedIndex = 0;
  64.             comboBox3.Text = myConfing.ConfingGetValue("Parity");
  65.             if (comboBox3.Text == "")
  66.             {
  67.                 comboBox3.Text = "None";
  68.             }

  69.             //列出數(shù)據(jù)位
  70.             ss = new string[] { "5", "6", "7", "8", "9", "10" };
  71.             comboBox4.DataSource = ss;
  72.             //comboBox4.Text = "8";
  73.             comboBox4.Text = myConfing.ConfingGetValue("dataBits");
  74.             if (comboBox4.Text == "")
  75.             {
  76.                 comboBox4.SelectedIndex = 3;
  77.             }

  78.             //列出停止位
  79.             comboBox5.DataSource = Enum.GetNames(typeof(StopBits));
  80.             //comboBox5.Text = Enum.Format(typeof(StopBits), StopBits.One, "G");
  81.             comboBox5.Text = myConfing.ConfingGetValue("stopBits");
  82.             if (comboBox5.Text == "")
  83.             {
  84.                 comboBox5.SelectedIndex = 1;
  85.             }

  86.             button1.Text = "打開(kāi)串口";
  87.             //開(kāi)始執(zhí)行后臺(tái)操作
  88.             //backgroundWorker1.RunWorkerAsync();
  89.             checkBox1.Checked = true;
  90.             checkBox2.Checked = true;
  91.             checkBox3.Checked = true;
  92.             checkBox4.Checked = true;
  93.             #endregion
  94.             this.button3.Visible = false;
  95.         }

  96.         private void comboBox1_DropDown_1(object sender, EventArgs e)
  97.         {
  98.             try
  99.             {
  100.                 comboBox1.Items.Clear();
  101.                 foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測(cè)
  102.                     comboBox1.Items.Add(com);
  103.             }
  104.             catch (Exception er)
  105.             {
  106.                 MessageBox.Show("端口加載失。" + er.Message, "提示");
  107.             }
  108.         }

  109.         #region 打開(kāi)串口按鈕處理
  110.         public void RefrespictureBox1()//刷新打開(kāi)串口按鍵顯示以及顏色
  111.         {
  112.             if (serialPort1.IsOpen)
  113.             {
  114.                 button1.BackColor = SystemColors.GradientActiveCaption;
  115.                 button1.Text = "關(guān)閉串口";
  116.             }
  117.             else
  118.             {
  119.                 button1.BackColor = SystemColors.Control;
  120.                 button1.Text = "打開(kāi)串口";
  121.             }
  122.             myConfing.SetValue("COM", comboBox1.Text);
  123.             myConfing.SetValue("buadRate", comboBox2.Text);
  124.             myConfing.SetValue("Parity", comboBox3.Text);
  125.             myConfing.SetValue("dataBits", comboBox4.Text);
  126.             myConfing.SetValue("stopBits", comboBox5.Text);
  127.         }

  128.         private void button1_Click(object sender, EventArgs e)//打開(kāi)串口
  129.         {
  130.             try
  131.             {
  132.                 if (serialPort1.IsOpen)//如果串口是開(kāi)的則關(guān)閉
  133.                 {
  134.                     serialPort1.Close();
  135.                     comboBox1.Enabled = true;
  136.                     comboBox2.Enabled = true;
  137.                     comboBox3.Enabled = true;
  138.                     comboBox4.Enabled = true;
  139.                     comboBox5.Enabled = true;
  140.                     #region
  141.                     //button1.Text = "打開(kāi)串口";
  142.                     /*//關(guān)閉串口后,串口設(shè)置選項(xiàng)便可以繼續(xù)使用
  143.                     comboBox1.Enabled = true;
  144.                     comboBox2.Enabled = true;
  145.                     comboBox3.Enabled = true;
  146.                     comboBox4.Enabled = true;
  147.                     comboBox5.Enabled = true;*/
  148.                     #endregion
  149.                 }
  150.                 else//否則打開(kāi)串口
  151.                 {
  152.                     //button1.Text = "關(guān)閉串口";
  153.                     serialPort1.PortName = comboBox1.Text;
  154.                     serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
  155.                     serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.Text);
  156.                     serialPort1.DataBits = Int32.Parse(comboBox4.Text);
  157.                     serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text);
  158.                     serialPort1.Encoding = Encoding.GetEncoding("Gb2312");//返回與指定代碼頁(yè)名稱關(guān)聯(lián)的編碼Gb2312
  159.                     serialPort1.Open();
  160.                     comboBox1.Enabled = false;
  161.                     comboBox2.Enabled = false;
  162.                     comboBox3.Enabled = false;
  163.                     comboBox4.Enabled = false;
  164.                     comboBox5.Enabled = false;
  165.                 }
  166.                 RefrespictureBox1();//刷新打開(kāi)串口按鍵顯示以及顏色
  167.             }
  168.             catch (Exception)
  169.             {
  170.                 //打開(kāi)串口失敗后,相應(yīng)標(biāo)志位取消
  171.                 MessageBox.Show("串口無(wú)效或已被占用!", "錯(cuò)誤提示");
  172.             }
  173.         }
  174.         #endregion

  175.         #region 發(fā)送區(qū)形式處理、串口按鍵發(fā)送、定時(shí)自動(dòng)發(fā)送以及其他外部調(diào)用發(fā)送相關(guān)接口
  176.         private bool CheckSendData()//檢查串口發(fā)送區(qū)域
  177.         {
  178.             if (textBox2.Text.Trim() == "") return false;
  179.             return true;
  180.         }

  181.         private void checkBox4_CheckedChanged(object sender, EventArgs e)//發(fā)送區(qū)HEX處理
  182.         {
  183.             string s = "";
  184.             if (checkBox4.CheckState == CheckState.Checked)//發(fā)送HEX顯示
  185.             {
  186.                 byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(textBox2.Text);
  187.                 textBox2.Text = "";
  188.                 foreach (byte btmp in by)
  189.                 {
  190.                     s = "00" + string.Format("{0:X}", btmp);
  191.                     textBox2.Text += s.Substring(s.Length - 2, 2);
  192.                     textBox2.Text += " ";
  193.                 }
  194.             }
  195.             else//發(fā)送ASCII顯示
  196.             {
  197.                 ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
  198.                 byte[] by = new byte[al.Count];
  199.                 int i = 0;
  200.                 foreach (string stmp in al)
  201.                 {
  202.                     by[i] += Convert.ToByte(stmp, 16);
  203.                     i++;
  204.                 }
  205.                 textBox2.Text = Encoding.GetEncoding("Gb2312").GetString(by);
  206.             }
  207.         }

  208.         private void textBox2_KeyPress(object sender, KeyPressEventArgs e)//發(fā)送區(qū)有按鍵鍵入,
  209.         {
  210.             if (checkBox1.CheckState == CheckState.Checked)//HEX發(fā)送時(shí)
  211.             {
  212.                 if (!Uri.IsHexDigit(e.KeyChar) && e.KeyChar != ' ')//不符合HEX的鍵入清除
  213.                 {
  214.                     e.KeyChar = (char)0;
  215.                 }
  216.             }
  217.         }

  218.         private void button2_Click(object sender, EventArgs e)//按鍵發(fā)送
  219.         {
  220.             try
  221.             {
  222.                 if (serialPort1.IsOpen)
  223.                 {
  224.                     /*if (!CheckSendData())//檢測(cè)要發(fā)送的數(shù)據(jù)
  225.                     {
  226.                         MessageBox.Show("請(qǐng)輸入要發(fā)送的數(shù)據(jù)!", "錯(cuò)誤提示");
  227.                         return;
  228.                     }*/
  229.                     string s = "";
  230.                     //MessageBox.Show(checkBox4.Checked.ToString());
  231.                     if (checkBox4.Checked)//十六進(jìn)制發(fā)送
  232.                     {
  233.                         ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
  234.                         byte[] by = new byte[al.Count];
  235.                         int i = 0;
  236.                         foreach (string stmp in al)
  237.                         {
  238.                             by[i] += Convert.ToByte(stmp, 16);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無(wú)符號(hào)整數(shù)。
  239.                             i++;
  240.                         }
  241.                         serialPort1.Write(by, 0, i);//發(fā)送字節(jié)
  242.                         //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時(shí),將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個(gè)字符串。。
  243.                     }
  244.                     else//ASCII發(fā)送
  245.                     {
  246.                         s = textBox2.Text;
  247.                         serialPort1.Write(s);//串口發(fā)送字符串

  248.                     }
  249.                     //MessageBox.Show(s);                    
  250.                 }
  251.                 else
  252.                 {
  253.                     MessageBox.Show("串口未打開(kāi)!", "錯(cuò)誤提示");
  254.                 }

  255.             }
  256.             catch (Exception)
  257.             {
  258.                 MessageBox.Show("發(fā)送數(shù)據(jù)時(shí)發(fā)生錯(cuò)誤!", "錯(cuò)誤提示");
  259.             }
  260.         }

  261.         public void sendData(string dataIn)//調(diào)用的發(fā)送函數(shù)
  262.         {
  263.             try
  264.             {
  265.                 if (serialPort1.IsOpen)
  266.                 {
  267.                     /*if (!CheckSendData())//檢測(cè)要發(fā)送的數(shù)據(jù)
  268.                     {
  269.                         MessageBox.Show("請(qǐng)輸入要發(fā)送的數(shù)據(jù)!", "錯(cuò)誤提示");
  270.                         return;
  271.                     }*/
  272.                     string s = "";
  273.                     textBox2.Text = dataIn;
  274.                     //MessageBox.Show(checkBox4.Checked.ToString());
  275.                     if (checkBox4.Checked)//十六進(jìn)制發(fā)送
  276.                     {
  277.                         ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
  278.                         byte[] by = new byte[al.Count];
  279.                         int i = 0;
  280.                         foreach (string stmp in al)
  281.                         {
  282.                             by[i] += Convert.ToByte(stmp, 16);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無(wú)符號(hào)整數(shù)。
  283.                             i++;
  284.                         }
  285.                         serialPort1.Write(by, 0, i);//發(fā)送字節(jié)
  286.                         //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時(shí),將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個(gè)字符串。。
  287.                     }
  288.                     else//ASCII發(fā)送
  289.                     {

  290.                         s = textBox2.Text;

  291.                         serialPort1.Write(s);//串口發(fā)送字符串

  292.                     }
  293.                     //MessageBox.Show(s);                    
  294.                 }
  295.                 else
  296.                 {
  297.                     MessageBox.Show("串口未打開(kāi)!", "錯(cuò)誤提示");
  298.                 }

  299.             }
  300.             catch (Exception)
  301.             {
  302.                 MessageBox.Show("發(fā)送數(shù)據(jù)時(shí)發(fā)生錯(cuò)誤!", "錯(cuò)誤提示");
  303.             }
  304.         }

  305.         public void sendData_NoDispaly(string dataIn)//調(diào)用的發(fā)送函數(shù)并且不顯示在發(fā)送區(qū)域
  306.         {
  307.             try
  308.             {
  309.                 if (serialPort1.IsOpen)
  310.                 {
  311.                     /*if (!CheckSendData())//檢測(cè)要發(fā)送的數(shù)據(jù)
  312.                     {
  313.                         MessageBox.Show("請(qǐng)輸入要發(fā)送的數(shù)據(jù)!", "錯(cuò)誤提示");
  314.                         return;
  315.                     }*/
  316.                     string s = "";
  317.                     //textBox2.Text = dataIn;//不顯示在發(fā)送區(qū)域
  318.                     //MessageBox.Show(checkBox4.Checked.ToString());
  319.                     if (checkBox4.Checked)//十六進(jìn)制發(fā)送
  320.                     {
  321.                         ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
  322.                         byte[] by = new byte[al.Count];
  323.                         int i = 0;
  324.                         foreach (string stmp in al)
  325.                         {
  326.                             by[i] += Convert.ToByte(stmp, 16);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無(wú)符號(hào)整數(shù)。
  327.                             i++;
  328.                         }
  329.                         serialPort1.Write(by, 0, i);//發(fā)送字節(jié)
  330.                         //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時(shí),將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個(gè)字符串。。
  331.                     }
  332.                     else//ASCII發(fā)送
  333.                     {

  334.                         s = textBox2.Text;

  335.                         serialPort1.Write(s);//串口發(fā)送字符串

  336.                     }
  337.                     //MessageBox.Show(s);                    
  338.                 }
  339.                 else
  340.                 {
  341.                     MessageBox.Show("串口未打開(kāi)!", "錯(cuò)誤提示");
  342.                 }

  343.             }
  344.             catch (Exception)
  345.             {
  346.                 MessageBox.Show("發(fā)送數(shù)據(jù)時(shí)發(fā)生錯(cuò)誤!", "錯(cuò)誤提示");
  347.             }
  348.         }

  349.         private void timer1_Tick(object sender, EventArgs e)//定時(shí)自動(dòng)發(fā)送
  350.         {
  351.             timer1.Interval = Convert.ToInt32(textBox1.Text);
  352.             try
  353.             {
  354.                 if ((serialPort1.IsOpen) && (checkBox5.Checked == true))
  355.                 {
  356.                     /*if (!CheckSendData())//檢測(cè)要發(fā)送的數(shù)據(jù)
  357.                     {
  358.                         MessageBox.Show("請(qǐng)輸入要發(fā)送的數(shù)據(jù)!", "錯(cuò)誤提示");
  359.                         return;
  360.                     }*/

  361.                     string s = "";
  362.                     //textBox2.Text = dataIn;
  363.                     //MessageBox.Show(checkBox4.Checked.ToString());
  364.                     if (checkBox4.Checked)//十六進(jìn)制發(fā)送
  365.                     {
  366.                         ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
  367.                         byte[] by = new byte[al.Count];
  368.                         int i = 0;
  369.                         foreach (string stmp in al)
  370.                         {
  371.                             by[i] += Convert.ToByte(stmp, 16);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無(wú)符號(hào)整數(shù)。
  372.                             i++;
  373.                         }
  374.                         serialPort1.Write(by, 0, i);//發(fā)送字節(jié)
  375.                         //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時(shí),將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個(gè)字符串。。
  376.                     }
  377.                     else//ASCII發(fā)送
  378.                     {

  379.                         s = textBox2.Text;

  380.                         serialPort1.Write(s);//串口發(fā)送字符串

  381.                     }
  382.                     send_count++;
  383.                     textBox5.Text = send_count.ToString();

  384.                 }
  385.                 else
  386.                 {
  387.                     //MessageBox.Show("串口未打開(kāi)!", "錯(cuò)誤提示");
  388.                 }

  389.             }
  390.             catch (Exception)
  391.             {
  392.                 //MessageBox.Show("發(fā)送數(shù)據(jù)時(shí)發(fā)生錯(cuò)誤!", "錯(cuò)誤提示");
  393.             }

  394.         }
  395.         #endregion

  396.         #region 接收方法一用到的線程處理,不用
  397.         delegate void SetTextCallback(string text);//委托,使用回調(diào)函數(shù)時(shí)考慮使用

  398.         private void SetText(string text)
  399.         {
  400.             try
  401.             {
  402.                 if (this.richTextBox1.InvokeRequired)//獲取一個(gè)值,該值指示調(diào)用方在對(duì)控件進(jìn)行方法調(diào)用時(shí)是否必須調(diào)用 Invoke 方法,因?yàn)檎{(diào)用方位于創(chuàng)建控件所在的線程以外的線程中。
  403.                 {
  404.                     SetTextCallback d = new SetTextCallback(SetText);//回調(diào)函數(shù)
  405.                     this.Invoke(d, new object[] { text });//執(zhí)行delegate里的搭載函數(shù)
  406.                 }
  407.                 else
  408.                 {
  409.                     this.richTextBox1.Text += text;
  410.                 }
  411.                 //this.richTextBox2.Focus();//獲取焦點(diǎn)
  412.                 //this.richTextBox2.Select(this.richTextBox2.TextLength, 0);//光標(biāo)定位到文本最后
  413.                 /* //設(shè)定光標(biāo)所在位置
  414.                  this.richTextBox1.SelectionStart = richTextBox1.TextLength;
  415.                  //滾動(dòng)到當(dāng)前光標(biāo)處
  416.                  this.richTextBox1.ScrollToCaret();*/
  417.             }
  418.             catch (Exception)
  419.             {
  420.             }
  421.         }
  422.         #endregion

  423.         #region 串口接收處理
  424.         //int receive_count_test = 0;
  425.         private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//清除接收
  426.         {
  427.             richTextBox1.Text = "";
  428.             send_count = 0;
  429.             //receive_count_test = 0;
  430.             textBox5.Text = "";
  431.             //textBox5.Text = "";
  432.         }

  433.         private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)//接收事件觸發(fā)
  434.         {
  435.             #region
  436.             /* char[] c;
  437.             //StringBuilder builder = new StringBuilder();//避免在事件處理方法中反復(fù)的創(chuàng)建,定義到外面。
  438.             try
  439.             {
  440.                 if (serialPort1.IsOpen)
  441.                 {
  442.                     c = new char[serialPort1.BytesToRead];
  443.                     serialPort1.Read(c, 0, c.Length);//串口讀取
  444.                     if (c.Length > 0)
  445.                     {
  446.                         if (checkBox1.Checked)//接收HEX顯示
  447.                         {
  448.                             if (checkBox3.Checked)//接收時(shí)間顯示
  449.                             {
  450.                                 SetText(DateTime.Now.ToString());
  451.                                 SetText(" ");
  452.                             }
  453.                             byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(c);
  454.                             myBy = by;
  455.                             myByLenth = by.Length;
  456.                             /*if (by[0] == 0x7b)
  457.                             {
  458.                                 MessageBox.Show("正確");
  459.                             }
  460.                             else
  461.                             {
  462.                                 MessageBox.Show(by[0].ToString());
  463.                             }*
  464.                             foreach (byte btmp in by)
  465.                             {
  466.                                 string s = "00" + string.Format("{0:X}", btmp);//將指定字符串中的一個(gè)或多個(gè)格式項(xiàng)替換為指定對(duì)象的字符串表示形式
  467.                                 s = s.Substring(s.Length - 2, 2);
  468.                                 SetText(new string(s.ToCharArray()));
  469.                                 SetText(" ");
  470.                             }
  471.                             if (checkBox2.Checked)//接收換行顯示
  472.                             {
  473.                                 SetText("\n");
  474.                             }
  475.                         }
  476.                         else
  477.                         {
  478.                             if (checkBox3.Checked)//接收時(shí)間顯示
  479.                             {
  480.                                 SetText(DateTime.Now.ToString());
  481.                             }
  482.                             SetText(new string(c));
  483.                             if (checkBox3.Checked)//接收換行顯示
  484.                             {
  485.                                 SetText("\n");
  486.                             }
  487.                         }
  488.                         //this.richTextBox2.Text += "\n";
  489.                     }
  490.                 }
  491.             }
  492.             catch (Exception)
  493.             {

  494.             }
  495.             if (checkBox2.Checked)//接收HEX顯示
  496.             {
  497.                 Thread.Sleep(500);//延時(shí)500ms 等待接收完數(shù)據(jù)
  498.             }
  499.             else
  500.             {
  501.                 Thread.Sleep(10);//延時(shí)100ms 等待接收完數(shù)據(jù)
  502.             }*/
  503.             /* //設(shè)定光標(biāo)所在位置
  504.              this.richTextBox1.SelectionStart = richTextBox1.TextLength;
  505.              //滾動(dòng)到當(dāng)前光標(biāo)處
  506.              this.richTextBox1.ScrollToCaret();*/

  507.             //追加的形式添加到文本框末端,并滾動(dòng)到最后。
  508.             //this.richTextBox1.AppendText(builder.ToString());
  509.             #endregion
  510.             #region
  511.             Thread.Sleep(Convert.ToInt32(textBox5.Text.Trim()));//延時(shí)100ms 等待接收完數(shù)據(jù)
  512.             //第二種接收方式
  513.             StringBuilder builder = new StringBuilder();//避免在事件處理方法中反復(fù)的創(chuàng)建,定義到外面。
  514.             long received_count = 0;//接收計(jì)數(shù)
  515.             int n = serialPort1.BytesToRead;//先記錄下來(lái),避免某種原因,人為的原因,操作幾次之間時(shí)間長(zhǎng),緩存不一致
  516.             byte[] buf = new byte[n];//聲明一個(gè)臨時(shí)數(shù)組存儲(chǔ)當(dāng)前來(lái)的串口數(shù)據(jù)
  517.             received_count += n;//增加接收計(jì)數(shù)
  518.             serialPort1.Read(buf, 0, n);//讀取緩沖數(shù)據(jù)
  519.             builder.Clear();//清除字符串構(gòu)造器的內(nèi)容

  520.             myBy = buf;
  521.             myByLenth = buf.Length;

  522.             //因?yàn)橐L問(wèn)ui資源,所以需要使用invoke方式同步ui。
  523.             this.Invoke((EventHandler)(delegate
  524.             {

  525.                 if (checkBox3.Checked)//接收時(shí)間顯示
  526.                 {
  527.                     this.richTextBox1.AppendText(DateTime.Now.ToString(@"yyyy\:MM\:dd") + " ");
  528.                     this.richTextBox1.AppendText(DateTime.Now.ToString(@"HH\:mm\:ss\:fff") + "  ");
  529.                 }

  530.                 //判斷是否是顯示為16禁止
  531.                 if (checkBox1.Checked)
  532.                 {
  533.                     //依次的拼接出16進(jìn)制字符串
  534.                     foreach (byte b in buf)
  535.                     {
  536.                         builder.Append(b.ToString("X2") + " ");//在此實(shí)例的結(jié)尾追加指定字符串的副本
  537.                     }
  538.                 }
  539.                 else
  540.                 {
  541.                     //直接按ASCII規(guī)則轉(zhuǎn)換成字符串
  542.                     builder.Append(Encoding.ASCII.GetString(buf));
  543.                 }
  544.                 //追加的形式添加到文本框末端,并滾動(dòng)到最后。
  545.                 this.richTextBox1.AppendText(builder.ToString());
  546.                 myStr = builder.ToString();//字符串輸出

  547.                 if (checkBox2.Checked)//接收換行顯示
  548.                 {
  549.                     this.richTextBox1.AppendText("\n");
  550.                 }
  551.                 //修改接收計(jì)數(shù)
  552.                 //labelGetCount.Text = "Get:" + received_count.ToString();
  553.                 try
  554.                 {
  555.                     if (receiveDtatFlag == true)//保存數(shù)據(jù)
  556.                     {
  557.                         string fName = saveFileDialog1.FileName;
  558.                         FileStream fs = File.Open(fName, FileMode.Append);
  559.                         StreamWriter sw = new StreamWriter(fs);

  560.                         if (checkBox3.Checked)//接收時(shí)間顯示
  561.                         {
  562.                             //this.richTextBox1.AppendText(DateTime.Now.ToString() + " ");
  563.                             sw.Write(DateTime.Now.ToString(@"hh\:mm\:ss\:fff") + " ");
  564.                         }
  565.                         sw.Write(builder.ToString());
  566.                         if (checkBox2.Checked)//接收換行顯示
  567.                         {
  568.                             sw.WriteLine("\n");

  569.                         }

  570.                         //sw.WriteLine(richTextBox1.Text);
  571.                         //textBox3.Text = fName;
  572.                         sw.Close();
  573.                         fs.Close();
  574.                     }
  575.                 }
  576.                 catch
  577.                 {

  578.                 }

  579.                 //analysis myans = new analysis();
  580.                 //myans.analysisData(myStr);
  581.             }));//*/
  582.             #endregion

  583.         }

  584.         private void richTextBox1_TextChanged(object sender, EventArgs e)//接收窗處理
  585.         {
  586.             if (richTextBox1.Lines.Length > 8000)//大于8000行時(shí)清楚前面的
  587.             {
  588.                 int n = 500;
  589.                 int start = richTextBox1.GetFirstCharIndexFromLine(0);//第一行第一個(gè)字符索引
  590.                 int end = richTextBox1.GetFirstCharIndexFromLine(n);//第n行第一個(gè)字符索引
  591.                 richTextBox1.Select(start, end);//選中n行
  592.                 richTextBox1.SelectedText = "";//設(shè)置前n行為空

  593.             }
  594.             richTextBox1.Focus();
  595.             richTextBox1.Select(richTextBox1.TextLength, 0);

  596.         }
  597.         #endregion

  598.         #region 窗體處理
  599.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)//關(guān)閉提醒
  600.         {
  601.             Properties.Settings.Default.Save();
  602.             myConfing.SetValue("COM", comboBox1.Text);
  603.             myConfing.SetValue("buadRate", comboBox2.Text);
  604.             myConfing.SetValue("Parity", comboBox3.Text);
  605.             myConfing.SetValue("dataBits", comboBox4.Text);
  606.             myConfing.SetValue("stopBits", comboBox5.Text);
  607.             if (DialogResult.Yes == MessageBox.Show("程序正在使用中,確認(rèn)退出?", "確認(rèn)退出", MessageBoxButtons.YesNo))
  608.             {
  609.                 //MessageBox.Show("立即退出!");

  610.                 serialPort1.Close();
  611.                 this.Dispose();
  612.                 e.Cancel = false;
  613.             }
  614.             else
  615.             {
  616.                 e.Cancel = true;
  617.             }
  618.         }

  619.         private void Form1_FormClosed(object sender, FormClosedEventArgs e)//關(guān)閉整個(gè)窗口
  620.         {
  621.             Properties.Settings.Default.Save();
  622.             myConfing.SetValue("COM", comboBox1.Text);
  623.             myConfing.SetValue("buadRate", comboBox2.Text);
  624.             myConfing.SetValue("Parity", comboBox3.Text);
  625.             myConfing.SetValue("dataBits", comboBox4.Text);
  626.             myConfing.SetValue("stopBits", comboBox5.Text);

  627.         }

  628.         private void button3_Click(object sender, EventArgs e)//窗口隱藏
  629.         {
  630.             //this.Hide();//隱藏窗體
  631.         }
  632.         #endregion

  633.         #region  數(shù)據(jù)文件保存處理
  634.         private void button4_Click(object sender, EventArgs e)//保存路徑選擇
  635.         {
  636.             //saveFileDialog1.InitialDirectory = @"G:\自制軟件\C#練習(xí)\20.19 文件保存SaveFileDialog控件\51zxw";
  637.             saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
  638.             saveFileDialog1.FilterIndex = 1;
  639.             saveFileDialog1.FileName = "ReceiveData";
  640.             if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  641.             {
  642.                 string fName = saveFileDialog1.FileName;
  643.                 FileStream fs = File.Open(fName, FileMode.Append);
  644.                 StreamWriter sw = new StreamWriter(fs);
  645.                 //sw.WriteLine(richTextBox1.Text);
  646.                 textBox3.Text = fName;
  647.                 sw.Close();
  648.                 fs.Close();

  649.             }
  650.         }

  651.         private void checkBox6_CheckedChanged(object sender, EventArgs e)//保存數(shù)據(jù)勾選處理
  652.         {
  653.             if (checkBox6.CheckState == CheckState.Checked)//選中
  654.             {
  655.                 receiveDtatFlag = true;
  656.             }
  657.             else
  658.             {
  659.                 receiveDtatFlag = false;
  660.             }
  661.         }
  662.         #endregion

  663.         #region 沒(méi)有使用
  664.         public void portIDGet()//串口自動(dòng)獲取
  665.         {
  666.             try
  667.             {
  668.                 comboBox1.Items.Clear();
  669.                 foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測(cè)
  670.                 {
  671.                     comboBox1.Items.Add(com);
  672.                 }

  673.                 //comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加載

  674.             }
  675.             catch (Exception er)
  676.             {
  677.                 MessageBox.Show("端口加載失。" + er.Message, "提示");
  678.             }
  679.         }
  680.         private void comboBox1_DragDrop(object sender, DragEventArgs e)
  681.         {
  682.             portIDGet();
  683.         }

  684.         private void comboBox1_DropDown(object sender, EventArgs e)
  685.         {
  686.             portIDGet();
  687.         }
  688.         #endregion


  689.     }
  690. }
復(fù)制代碼

作者: hefeng898961    時(shí)間: 2018-8-24 18:24
感謝分享
作者: Go_Sun_Way    時(shí)間: 2019-10-11 15:14
非常不錯(cuò),標(biāo)記一下




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1