VS2010 C#串列埠除錯助手
阿新 • • 發佈:2019-01-11
2017.10.18更新:
1.加入停止顯示接收的字元。
2.加入定時傳送功能,可以迴圈傳送。
4.串列埠名稱支援漢字顯示,例如:COM1:通訊埠,
COM4: USB-SERIAL CH340
3.修改部分bug。
完整的工程已經上傳到我的csdn資源,需要的可以下載!
下載
1.基於vs2010,c#串列埠。
2.支援熱插拔。
3.支援儲存接收檔案txt格式,可與微控制器串列埠連線傳送資料。
4.視窗狀態列顯示。
5.登陸介面
6.顯示漢字
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;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Threading;
namespace TEST
{
public partial class Serial : Form
{
public Serial()
{
InitializeComponent();
}
private SerialPort comm = new SerialPort();
private StringBuilder builder = new StringBuilder();
private long received_count = 0;//接收計數
private long send_count = 0;//傳送計數
private string resultFile;
private void Serial_Load(object sender, EventArgs e)
{
//初始化下拉串列埠名稱列表框
string[] ports = SerialPort.GetPortNames();
Array.Sort(ports);//排序
comboPortName.Items.AddRange(ports);
comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("9600");
comboBoxstopb.SelectedIndex = comboBoxstopb.Items.IndexOf("1");
comboBoxdateb.SelectedIndex = comboBoxdateb.Items.IndexOf("8");
comboBoxjiou.SelectedIndex = comboBoxjiou.Items.IndexOf("無");
// comm.NewLine = "/r/n";
// comm.RtsEnable = true;
comm.DataReceived += comm_DataReceived;
txSend.Text = "01 02 03 04 05 06 07 08";
buttonSend.Enabled = false;
toolStripStatusLabel5.Text = " " + DateTime.Now.ToString();
}
private void Serial_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void buttonopen_Click(object sender, EventArgs e)
{
//根據當前串列埠物件,來判斷操作
if (comm.IsOpen)
{
//開啟時點選,則關閉串列埠
comm.Close();
}
else
{
if (comboPortName.Text =="")
{
MessageBox.Show("請插入串列埠裝置!");
return;
}
//關閉時點選,則設定好埠,波特率後開啟
comm.PortName = comboPortName.Text;
comm.BaudRate = int.Parse(comboBaudrate.Text);
try
{
comm.Open();
}
catch (Exception ex)
{
//捕獲到異常資訊,建立一個新的comm物件,之前的不能用了。
// comm = new SerialPort();
//現實異常資訊給客戶。
MessageBox.Show(ex.Message);
}
}
//設定按鈕的狀態
buttonopen.Text = comm.IsOpen ? "關閉串列埠" : "開啟串列埠";
buttonSend.Enabled = comm.IsOpen ? true:false;
labelopenflag.ForeColor = comm.IsOpen ? Color.Red : Color.Black;
}
void comm_DataReceived(object sender, EventArgs e)
{
int n = comm.BytesToRead;//獲取快取區位元組數
byte[] buf = new byte[n];//儲存串列埠資料用
received_count += n;//接收計數
comm.Read(buf, 0, n);//讀取緩衝資料
builder.Clear();//清除字串構造器的內容
//因為要訪問ui資源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
//判斷是否是顯示為16禁止
if (checkBoxHexView.Checked)
{
//依次的拼接出16進位制字串
foreach (byte b in buf)
{
builder.Append(b.ToString("X2") + " ");
}
}
else
{
//直接按ASCII規則轉換成字串
builder.Append(Encoding.Default.GetString(buf));
}
//追加的形式新增到文字框末端,並滾動到最後。
this.txGet.AppendText(builder.ToString());
//修改接收計數
toolStripStatusLabel4.Text = "Recv:" + received_count.ToString();
}));
}
private void buttonSend_Click(object sender, EventArgs e)
{
bool lineflag=false;
//定義一個變數,記錄傳送了幾個位元組
int n = 0;
if (checkBoxNewlineSend.Checked)
{
lineflag = true;
}
//16進位制傳送
if (checkBoxHexSend.Checked)
{
//正則得到有效的十六進位制數(?i)對大小寫不敏感,[/da-f],{2}連續出現2次
// MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[/da-f]{2}");
MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[\da-f]{2}");
List<byte> buf = new List<byte>();//填充到這個臨時列表中
//依次新增到列表中
foreach (Match m in mc)
{
buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));
}
//轉換列表為陣列後傳送
comm.Write(buf.ToArray(), 0, buf.Count);
if (lineflag == true)
{ //記錄傳送的位元組數
comm.WriteLine("\r\n");
n = buf.Count+2;
}
else
n = buf.Count;
}
else//ascii編碼直接傳送
{
if (lineflag == true)
{
comm.Write(txSend.Text+"\r\n");
n = txSend.Text.Length + 2;
}
else//不包含換行符
{
comm.Write(txSend.Text);
n = txSend.Text.Length;
}
}
send_count += n;//累加發送位元組數
toolStripStatusLabel3.Text = "Send:" + send_count.ToString();
}
private void buttonReset_Click(object sender, EventArgs e)
{
txSend.Clear();
send_count = 0;
toolStripStatusLabel3.Text = "Send:0";
}
private void btncleanrec_Click(object sender, EventArgs e)
{
txGet.Clear();
received_count = 0;
toolStripStatusLabel4.Text = "Recv:0";
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
txGet.BackColor = Color.Black;
txGet.ForeColor = Color.GreenYellow;
}
else
{
txGet.BackColor = Color.White;
txGet.ForeColor = Color.Black;
}
}
//熱插拔
protected override void DefWndProc(ref Message m)
{
if (m.Msg == 0x0219)
{
if (comm.IsOpen==false)
{
bool flag = true;
string[] portnames = SerialPort.GetPortNames();
for (int i = 0; i < portnames.Length; i++)
{
if (comm.PortName == portnames[i])
flag = false;//不是本串列埠被拔
}
if (flag == true)//所有存在的串列埠中找不到已經開啟的串列埠
{
comboPortName.Text="";
//comm.Close();
buttonopen.Text = comm.IsOpen ? "關閉串列埠" : "開啟串列埠";
buttonSend.Enabled = comm.IsOpen ? true : false;
labelopenflag.ForeColor = comm.IsOpen ? Color.Red : Color.Black;
}
}
}
base.DefWndProc(ref m);
}
private void comboPortName_Click(object sender, EventArgs e)
{
comboPortName.Items.Clear();
string[] ports1 = SerialPort.GetPortNames();
Array.Sort(ports1);//排序
comboPortName.Items.AddRange(ports1);
comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
}
private void timer1_Tick(object sender, EventArgs e)
{
toolStripStatusLabel5.Text=" "+DateTime.Now.ToString();
}
private void toolStripStatusLabel2_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://blog.csdn.net/xingkong886");
}
private void btnsave_Click(object sender, EventArgs e)
{
/*
if (txGet.Text == "")
{
MessageBox.Show("沒有資料儲存!","錯誤");
return;
}
*/
SaveFileDialog SaveFile = new SaveFileDialog();
// SaveFile.InitialDirectory = "E:\\1work\\FILE";//初始目錄
SaveFile.Filter = "All files(*.*)|*.*|txt files(*.txt)|*.txt";//文字篩選
SaveFile.FilterIndex = 3;//文字篩選器索引,選擇第一項就是1
SaveFile.RestoreDirectory = true;
if (SaveFile.ShowDialog() == DialogResult.OK)
{
resultFile = SaveFile.FileName;
StreamWriter sw = File.CreateText(resultFile);
sw.WriteLine(DateTime.Now.ToString());
sw.Write(txGet.Text);
sw.Close();
}
}
}
}