c#寫的串口助手的運行界面:
0.png (16.73 KB, 下載次數: 61)
下載附件
2018-6-14 22:38 上傳
0.png (45.46 KB, 下載次數: 71)
下載附件
2018-6-14 22:38 上傳
全部源碼資料51hei下載地址:
4、COM_ok.zip
(3.58 MB, 下載次數: 116)
2018-6-14 20:51 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
部分源碼預覽:
- 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.Collections;
- using System.IO;
- namespace COM_A
- {
- public partial class Form1 : Form
- {
- public byte[] myBy;//傳遞串口接收到的數據
- public int myByLenth = 0;//串口接收到的數據長度
- public string myStr;//串口接收的字符串
- public bool receiveDtatFlag = false;
- public int send_count = 0;
- public Form1()
- {
- InitializeComponent();
- //this.ControlBox = false;//最小化最大化關閉按鈕處理
- }
- private void Form1_Load(object sender, EventArgs e)//頁面加載
- {
- #region 串口設置初始化加載
- try
- {
- foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測
- comboBox1.Items.Add(com);
- //comboBox1.Text = (string)comboBox1.Items[0];//初始化選擇串口
- comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加載
- if (comboBox1.Text == "")
- {
- comboBox1.Text = (string)comboBox1.Items[0];//初始化選擇串口
- }
- }
- catch (Exception er)
- {
- MessageBox.Show("端口加載失敗!" + er.Message, "提示");
- }
- //列出常用的波特率
- string[] ss = new string[] { "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "57600", "115200" };
- comboBox2.DataSource = ss;
- /*for (int temp = 0; temp < 10; temp++)
- {
- comboBox2.Items.Add(ss[temp]);
- }*/
- comboBox2.Text = myConfing.ConfingGetValue("buadRate");
- if (comboBox2.Text == "")
- {
- comboBox2.SelectedIndex = 3;
- }
- //comboBox2.SelectedIndex = 3;
- //列出奇偶校驗位
- comboBox3.DataSource = Enum.GetNames(typeof(Parity));
- //comboBox3.Items.Add("無校驗");
- //comboBox3.Items.Add("奇校驗");
- //comboBox3.Items.Add("偶校驗");
- //comboBox3.SelectedIndex = 0;
- comboBox3.Text = myConfing.ConfingGetValue("Parity");
- if (comboBox3.Text == "")
- {
- comboBox3.Text = "None";
- }
- //列出數據位
- ss = new string[] { "5", "6", "7", "8", "9", "10" };
- comboBox4.DataSource = ss;
- //comboBox4.Text = "8";
- comboBox4.Text = myConfing.ConfingGetValue("dataBits");
- if (comboBox4.Text == "")
- {
- comboBox4.SelectedIndex = 3;
- }
- //列出停止位
- comboBox5.DataSource = Enum.GetNames(typeof(StopBits));
- //comboBox5.Text = Enum.Format(typeof(StopBits), StopBits.One, "G");
- comboBox5.Text = myConfing.ConfingGetValue("stopBits");
- if (comboBox5.Text == "")
- {
- comboBox5.SelectedIndex = 1;
- }
- button1.Text = "打開串口";
- //開始執行后臺操作
- //backgroundWorker1.RunWorkerAsync();
- checkBox1.Checked = true;
- checkBox2.Checked = true;
- checkBox3.Checked = true;
- checkBox4.Checked = true;
- #endregion
- this.button3.Visible = false;
- }
- private void comboBox1_DropDown_1(object sender, EventArgs e)
- {
- try
- {
- comboBox1.Items.Clear();
- foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測
- comboBox1.Items.Add(com);
- }
- catch (Exception er)
- {
- MessageBox.Show("端口加載失敗!" + er.Message, "提示");
- }
- }
- #region 打開串口按鈕處理
- public void RefrespictureBox1()//刷新打開串口按鍵顯示以及顏色
- {
- if (serialPort1.IsOpen)
- {
- button1.BackColor = SystemColors.GradientActiveCaption;
- button1.Text = "關閉串口";
- }
- else
- {
- button1.BackColor = SystemColors.Control;
- button1.Text = "打開串口";
- }
- myConfing.SetValue("COM", comboBox1.Text);
- myConfing.SetValue("buadRate", comboBox2.Text);
- myConfing.SetValue("Parity", comboBox3.Text);
- myConfing.SetValue("dataBits", comboBox4.Text);
- myConfing.SetValue("stopBits", comboBox5.Text);
- }
- private void button1_Click(object sender, EventArgs e)//打開串口
- {
- try
- {
- if (serialPort1.IsOpen)//如果串口是開的則關閉
- {
- serialPort1.Close();
- comboBox1.Enabled = true;
- comboBox2.Enabled = true;
- comboBox3.Enabled = true;
- comboBox4.Enabled = true;
- comboBox5.Enabled = true;
- #region
- //button1.Text = "打開串口";
- /*//關閉串口后,串口設置選項便可以繼續使用
- comboBox1.Enabled = true;
- comboBox2.Enabled = true;
- comboBox3.Enabled = true;
- comboBox4.Enabled = true;
- comboBox5.Enabled = true;*/
- #endregion
- }
- else//否則打開串口
- {
- //button1.Text = "關閉串口";
- serialPort1.PortName = comboBox1.Text;
- serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
- serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.Text);
- serialPort1.DataBits = Int32.Parse(comboBox4.Text);
- serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text);
- serialPort1.Encoding = Encoding.GetEncoding("Gb2312");//返回與指定代碼頁名稱關聯的編碼Gb2312
- serialPort1.Open();
- comboBox1.Enabled = false;
- comboBox2.Enabled = false;
- comboBox3.Enabled = false;
- comboBox4.Enabled = false;
- comboBox5.Enabled = false;
- }
- RefrespictureBox1();//刷新打開串口按鍵顯示以及顏色
- }
- catch (Exception)
- {
- //打開串口失敗后,相應標志位取消
- MessageBox.Show("串口無效或已被占用!", "錯誤提示");
- }
- }
- #endregion
- #region 發送區形式處理、串口按鍵發送、定時自動發送以及其他外部調用發送相關接口
- private bool CheckSendData()//檢查串口發送區域
- {
- if (textBox2.Text.Trim() == "") return false;
- return true;
- }
- private void checkBox4_CheckedChanged(object sender, EventArgs e)//發送區HEX處理
- {
- string s = "";
- if (checkBox4.CheckState == CheckState.Checked)//發送HEX顯示
- {
- byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(textBox2.Text);
- textBox2.Text = "";
- foreach (byte btmp in by)
- {
- s = "00" + string.Format("{0:X}", btmp);
- textBox2.Text += s.Substring(s.Length - 2, 2);
- textBox2.Text += " ";
- }
- }
- else//發送ASCII顯示
- {
- ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);
- i++;
- }
- textBox2.Text = Encoding.GetEncoding("Gb2312").GetString(by);
- }
- }
- private void textBox2_KeyPress(object sender, KeyPressEventArgs e)//發送區有按鍵鍵入,
- {
- if (checkBox1.CheckState == CheckState.Checked)//HEX發送時
- {
- if (!Uri.IsHexDigit(e.KeyChar) && e.KeyChar != ' ')//不符合HEX的鍵入清除
- {
- e.KeyChar = (char)0;
- }
- }
- }
- private void button2_Click(object sender, EventArgs e)//按鍵發送
- {
- try
- {
- if (serialPort1.IsOpen)
- {
- /*if (!CheckSendData())//檢測要發送的數據
- {
- MessageBox.Show("請輸入要發送的數據!", "錯誤提示");
- return;
- }*/
- string s = "";
- //MessageBox.Show(checkBox4.Checked.ToString());
- if (checkBox4.Checked)//十六進制發送
- {
- ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//將指定基的數字的字符串表示形式轉換為等效的 8 位無符號整數。
- i++;
- }
- serialPort1.Write(by, 0, i);//發送字節
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節數組中的所有字節解碼為一個字符串。。
- }
- else//ASCII發送
- {
- s = textBox2.Text;
- serialPort1.Write(s);//串口發送字符串
- }
- //MessageBox.Show(s);
- }
- else
- {
- MessageBox.Show("串口未打開!", "錯誤提示");
- }
- }
- catch (Exception)
- {
- MessageBox.Show("發送數據時發生錯誤!", "錯誤提示");
- }
- }
- public void sendData(string dataIn)//調用的發送函數
- {
- try
- {
- if (serialPort1.IsOpen)
- {
- /*if (!CheckSendData())//檢測要發送的數據
- {
- MessageBox.Show("請輸入要發送的數據!", "錯誤提示");
- return;
- }*/
- string s = "";
- textBox2.Text = dataIn;
- //MessageBox.Show(checkBox4.Checked.ToString());
- if (checkBox4.Checked)//十六進制發送
- {
- ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//將指定基的數字的字符串表示形式轉換為等效的 8 位無符號整數。
- i++;
- }
- serialPort1.Write(by, 0, i);//發送字節
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節數組中的所有字節解碼為一個字符串。。
- }
- else//ASCII發送
- {
- s = textBox2.Text;
- serialPort1.Write(s);//串口發送字符串
- }
- //MessageBox.Show(s);
- }
- else
- {
- MessageBox.Show("串口未打開!", "錯誤提示");
- }
- }
- catch (Exception)
- {
- MessageBox.Show("發送數據時發生錯誤!", "錯誤提示");
- }
- }
- public void sendData_NoDispaly(string dataIn)//調用的發送函數并且不顯示在發送區域
- {
- try
- {
- if (serialPort1.IsOpen)
- {
- /*if (!CheckSendData())//檢測要發送的數據
- {
- MessageBox.Show("請輸入要發送的數據!", "錯誤提示");
- return;
- }*/
- string s = "";
- //textBox2.Text = dataIn;//不顯示在發送區域
- //MessageBox.Show(checkBox4.Checked.ToString());
- if (checkBox4.Checked)//十六進制發送
- {
- ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//將指定基的數字的字符串表示形式轉換為等效的 8 位無符號整數。
- i++;
- }
- serialPort1.Write(by, 0, i);//發送字節
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節數組中的所有字節解碼為一個字符串。。
- }
- else//ASCII發送
- {
- s = textBox2.Text;
- serialPort1.Write(s);//串口發送字符串
- }
- //MessageBox.Show(s);
- }
- else
- {
- MessageBox.Show("串口未打開!", "錯誤提示");
- }
- }
- catch (Exception)
- {
- MessageBox.Show("發送數據時發生錯誤!", "錯誤提示");
- }
- }
- private void timer1_Tick(object sender, EventArgs e)//定時自動發送
- {
- timer1.Interval = Convert.ToInt32(textBox1.Text);
- try
- {
- if ((serialPort1.IsOpen) && (checkBox5.Checked == true))
- {
- /*if (!CheckSendData())//檢測要發送的數據
- {
- MessageBox.Show("請輸入要發送的數據!", "錯誤提示");
- return;
- }*/
- string s = "";
- //textBox2.Text = dataIn;
- //MessageBox.Show(checkBox4.Checked.ToString());
- if (checkBox4.Checked)//十六進制發送
- {
- ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//將指定基的數字的字符串表示形式轉換為等效的 8 位無符號整數。
- i++;
- }
- serialPort1.Write(by, 0, i);//發送字節
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節數組中的所有字節解碼為一個字符串。。
- }
- else//ASCII發送
- {
- s = textBox2.Text;
- serialPort1.Write(s);//串口發送字符串
- }
- send_count++;
- textBox5.Text = send_count.ToString();
- }
- else
- {
- //MessageBox.Show("串口未打開!", "錯誤提示");
- }
- }
- catch (Exception)
- {
- //MessageBox.Show("發送數據時發生錯誤!", "錯誤提示");
- }
- }
- #endregion
- #region 接收方法一用到的線程處理,不用
- delegate void SetTextCallback(string text);//委托,使用回調函數時考慮使用
- private void SetText(string text)
- {
- try
- {
- if (this.richTextBox1.InvokeRequired)//獲取一個值,該值指示調用方在對控件進行方法調用時是否必須調用 Invoke 方法,因為調用方位于創建控件所在的線程以外的線程中。
- {
- SetTextCallback d = new SetTextCallback(SetText);//回調函數
- this.Invoke(d, new object[] { text });//執行delegate里的搭載函數
- }
- else
- {
- this.richTextBox1.Text += text;
- }
- //this.richTextBox2.Focus();//獲取焦點
- //this.richTextBox2.Select(this.richTextBox2.TextLength, 0);//光標定位到文本最后
- /* //設定光標所在位置
- this.richTextBox1.SelectionStart = richTextBox1.TextLength;
- //滾動到當前光標處
- this.richTextBox1.ScrollToCaret();*/
- }
- catch (Exception)
- {
- }
- }
- #endregion
- #region 串口接收處理
- //int receive_count_test = 0;
- private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//清除接收
- {
- richTextBox1.Text = "";
- send_count = 0;
- //receive_count_test = 0;
- textBox5.Text = "";
- //textBox5.Text = "";
- }
- private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)//接收事件觸發
- {
- #region
- /* char[] c;
- //StringBuilder builder = new StringBuilder();//避免在事件處理方法中反復的創建,定義到外面。
- try
- {
- if (serialPort1.IsOpen)
- {
- c = new char[serialPort1.BytesToRead];
- serialPort1.Read(c, 0, c.Length);//串口讀取
- if (c.Length > 0)
- {
- if (checkBox1.Checked)//接收HEX顯示
- {
- if (checkBox3.Checked)//接收時間顯示
- {
- SetText(DateTime.Now.ToString());
- SetText(" ");
- }
- byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(c);
- myBy = by;
- myByLenth = by.Length;
- /*if (by[0] == 0x7b)
- {
- MessageBox.Show("正確");
- }
- else
- {
- MessageBox.Show(by[0].ToString());
- }*
- foreach (byte btmp in by)
- {
- string s = "00" + string.Format("{0:X}", btmp);//將指定字符串中的一個或多個格式項替換為指定對象的字符串表示形式
- s = s.Substring(s.Length - 2, 2);
- SetText(new string(s.ToCharArray()));
- SetText(" ");
- }
- if (checkBox2.Checked)//接收換行顯示
- {
- SetText("\n");
- }
- }
- else
- {
- if (checkBox3.Checked)//接收時間顯示
- {
- SetText(DateTime.Now.ToString());
- }
- SetText(new string(c));
- if (checkBox3.Checked)//接收換行顯示
- {
- SetText("\n");
- }
- }
- //this.richTextBox2.Text += "\n";
- }
- }
- }
- catch (Exception)
- {
- }
- if (checkBox2.Checked)//接收HEX顯示
- {
- Thread.Sleep(500);//延時500ms 等待接收完數據
- }
- else
- {
- Thread.Sleep(10);//延時100ms 等待接收完數據
- }*/
- /* //設定光標所在位置
- this.richTextBox1.SelectionStart = richTextBox1.TextLength;
- //滾動到當前光標處
- this.richTextBox1.ScrollToCaret();*/
- //追加的形式添加到文本框末端,并滾動到最后。
- //this.richTextBox1.AppendText(builder.ToString());
- #endregion
- #region
- Thread.Sleep(Convert.ToInt32(textBox5.Text.Trim()));//延時100ms 等待接收完數據
- //第二種接收方式
- StringBuilder builder = new StringBuilder();//避免在事件處理方法中反復的創建,定義到外面。
- long received_count = 0;//接收計數
- int n = serialPort1.BytesToRead;//先記錄下來,避免某種原因,人為的原因,操作幾次之間時間長,緩存不一致
- byte[] buf = new byte[n];//聲明一個臨時數組存儲當前來的串口數據
- received_count += n;//增加接收計數
- serialPort1.Read(buf, 0, n);//讀取緩沖數據
- builder.Clear();//清除字符串構造器的內容
- myBy = buf;
- myByLenth = buf.Length;
- //因為要訪問ui資源,所以需要使用invoke方式同步ui。
- this.Invoke((EventHandler)(delegate
- {
- if (checkBox3.Checked)//接收時間顯示
- {
- this.richTextBox1.AppendText(DateTime.Now.ToString(@"yyyy\:MM\:dd") + " ");
- this.richTextBox1.AppendText(DateTime.Now.ToString(@"HH\:mm\:ss\:fff") + " ");
- }
- //判斷是否是顯示為16禁止
- if (checkBox1.Checked)
- {
- //依次的拼接出16進制字符串
- foreach (byte b in buf)
- {
- builder.Append(b.ToString("X2") + " ");//在此實例的結尾追加指定字符串的副本
- }
- }
- else
- {
- //直接按ASCII規則轉換成字符串
- builder.Append(Encoding.ASCII.GetString(buf));
- }
- //追加的形式添加到文本框末端,并滾動到最后。
- this.richTextBox1.AppendText(builder.ToString());
- myStr = builder.ToString();//字符串輸出
- if (checkBox2.Checked)//接收換行顯示
- {
- this.richTextBox1.AppendText("\n");
- }
- //修改接收計數
- //labelGetCount.Text = "Get:" + received_count.ToString();
- try
- {
- if (receiveDtatFlag == true)//保存數據
- {
- string fName = saveFileDialog1.FileName;
- FileStream fs = File.Open(fName, FileMode.Append);
- StreamWriter sw = new StreamWriter(fs);
- if (checkBox3.Checked)//接收時間顯示
- {
- //this.richTextBox1.AppendText(DateTime.Now.ToString() + " ");
- sw.Write(DateTime.Now.ToString(@"hh\:mm\:ss\:fff") + " ");
- }
- sw.Write(builder.ToString());
- if (checkBox2.Checked)//接收換行顯示
- {
- sw.WriteLine("\n");
- }
- //sw.WriteLine(richTextBox1.Text);
- //textBox3.Text = fName;
- sw.Close();
- fs.Close();
- }
- }
- catch
- {
- }
- //analysis myans = new analysis();
- //myans.analysisData(myStr);
- }));//*/
- #endregion
- }
- private void richTextBox1_TextChanged(object sender, EventArgs e)//接收窗處理
- {
- if (richTextBox1.Lines.Length > 8000)//大于8000行時清楚前面的
- {
- int n = 500;
- int start = richTextBox1.GetFirstCharIndexFromLine(0);//第一行第一個字符索引
- int end = richTextBox1.GetFirstCharIndexFromLine(n);//第n行第一個字符索引
- richTextBox1.Select(start, end);//選中n行
- richTextBox1.SelectedText = "";//設置前n行為空
- }
- richTextBox1.Focus();
- richTextBox1.Select(richTextBox1.TextLength, 0);
- }
- #endregion
- #region 窗體處理
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)//關閉提醒
- {
- Properties.Settings.Default.Save();
- myConfing.SetValue("COM", comboBox1.Text);
- myConfing.SetValue("buadRate", comboBox2.Text);
- myConfing.SetValue("Parity", comboBox3.Text);
- myConfing.SetValue("dataBits", comboBox4.Text);
- myConfing.SetValue("stopBits", comboBox5.Text);
- if (DialogResult.Yes == MessageBox.Show("程序正在使用中,確認退出?", "確認退出", MessageBoxButtons.YesNo))
- {
- //MessageBox.Show("立即退出!");
- serialPort1.Close();
- this.Dispose();
- e.Cancel = false;
- }
- else
- {
- e.Cancel = true;
- }
- }
- private void Form1_FormClosed(object sender, FormClosedEventArgs e)//關閉整個窗口
- {
- Properties.Settings.Default.Save();
- myConfing.SetValue("COM", comboBox1.Text);
- myConfing.SetValue("buadRate", comboBox2.Text);
- myConfing.SetValue("Parity", comboBox3.Text);
- myConfing.SetValue("dataBits", comboBox4.Text);
- myConfing.SetValue("stopBits", comboBox5.Text);
- }
- private void button3_Click(object sender, EventArgs e)//窗口隱藏
- {
- //this.Hide();//隱藏窗體
- }
- #endregion
- #region 數據文件保存處理
- private void button4_Click(object sender, EventArgs e)//保存路徑選擇
- {
- //saveFileDialog1.InitialDirectory = @"G:\自制軟件\C#練習\20.19 文件保存SaveFileDialog控件\51zxw";
- saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
- saveFileDialog1.FilterIndex = 1;
- saveFileDialog1.FileName = "ReceiveData";
- if (saveFileDialog1.ShowDialog() == DialogResult.OK)
- {
- string fName = saveFileDialog1.FileName;
- FileStream fs = File.Open(fName, FileMode.Append);
- StreamWriter sw = new StreamWriter(fs);
- //sw.WriteLine(richTextBox1.Text);
- textBox3.Text = fName;
- sw.Close();
- fs.Close();
- }
- }
- private void checkBox6_CheckedChanged(object sender, EventArgs e)//保存數據勾選處理
- {
- if (checkBox6.CheckState == CheckState.Checked)//選中
- {
- receiveDtatFlag = true;
- }
- else
- {
- receiveDtatFlag = false;
- }
- }
- #endregion
- #region 沒有使用
- public void portIDGet()//串口自動獲取
- {
- try
- {
- comboBox1.Items.Clear();
- foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口檢測
- {
- comboBox1.Items.Add(com);
- }
- //comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加載
- }
- catch (Exception er)
- {
- MessageBox.Show("端口加載失敗!" + er.Message, "提示");
- }
- }
- private void comboBox1_DragDrop(object sender, DragEventArgs e)
- {
- portIDGet();
- }
- private void comboBox1_DropDown(object sender, EventArgs e)
- {
- portIDGet();
- }
- #endregion
- }
- }
復制代碼 |