📄 form1.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialComm
{
public partial class Form1 : Form
{
//===================================================
//申明全局变量。
public int CmdIdx = 0; //命令发送指针初始为0。
bool IsReceving = false; //接收数据标志。
bool DoingStr = false; //处理字符串标志。
bool DoingHex = false; //处理十六进制标志。
//===================================================
public Form1()
{
InitializeComponent();
}
private void IntToHex()
{
try
{
int Int = int.Parse(tbDec.Text);
string TempStr = Convert.ToString(Int, 16);
while(TempStr.Length < 8 )
TempStr = '0' + TempStr;
tbHex.Text = TempStr.ToUpper();
tbDec.SelectAll();
}
catch (Exception Err)
{
tbDec.SelectAll();
MessageBox.Show(Err.Message, "串口调试助手");
}
}
private void HexToInt()
{
try
{
int Int = Convert.ToInt32(tbHex.Text,16);
tbDec.Text = Int.ToString();
tbHex.SelectAll();
}
catch (Exception Err)
{
tbHex.SelectAll();
MessageBox.Show(Err.Message, "串口调试助手");
}
}
private void CmdClick(int idx)
{ //发送命令。
try
{
//自动打开端口。
if (!sComm.IsOpen)
btOpen_Click(null, null);
string TempStr = string.Empty;
switch(idx)
{
case 1:
TempStr = tbCmd1.Text;
break;
case 2:
TempStr = tbCmd2.Text;
break;
case 3:
TempStr = tbCmd3.Text;
break;
case 4:
TempStr = tbCmd4.Text;
break;
case 5:
TempStr = tbCmd5.Text;
break;
default:
return;
}
TempStr = DelSpace(TempStr);
if (cbDefFrm.Checked) //自动添加帧头帧尾和校验
{
TempStr=DelSpace(tbStart.Text)+TempStr; //加入头。
//转换为字节数组。
int Len=TempStr.Length; //待校验的字符串长度。
byte[] VerBin = new byte[Len / 2];
int j=0;
for(int i=0;i<Len;i+=2,j++)
{
VerBin[j] = Convert.ToByte(TempStr.Substring(i, 2), 16);
}
//计算校验字节。
byte VerByte=0;
if (rdXor.Checked)
{
for (int i = 0; i < VerBin.Length; i++)
VerByte ^= VerBin[i]; //异或校验。
}
else if (rdAdd.Checked)
{
for (int i = 0; i < VerBin.Length; i++)
VerByte += VerBin[i]; //和校验。
}
//校验字节转为HEX字符串。
string VerStr = Convert.ToString(VerByte, 16);
//合成一帧。
TempStr = TempStr + DelSpace(VerStr) + DelSpace(tbEnd.Text);
}
SendAsHex(TempStr);
}
catch (Exception err)
{
TimeHex.Stop();
TimeHex.Enabled = false;
MessageBox.Show(err.Message, "串口调试助手");
cbTimeHex.Checked = false;
}
}
private void ClrEncode()
{
lbHexData.Text = string.Empty;
tbByte1.Text = string.Empty;
tbByte2.Text = string.Empty;
tbByte3.Text = string.Empty;
tbByte4.Text = string.Empty;
tbUInt16L.Text = string.Empty;
tbUInt16R.Text = string.Empty;
tbUInt32.Text = string.Empty;
tbSByte1.Text = string.Empty;
tbSByte2.Text = string.Empty;
tbSByte3.Text = string.Empty;
tbSByte4.Text = string.Empty;
tbInt16L.Text = string.Empty;
tbInt16R.Text = string.Empty;
tbInt32.Text = string.Empty;
}
private void SendAsHex(string str)
{
int Len = str.Length;
//组包发送。
byte[] send = new byte[Len / 2];
int j = 0;
for (int i = 0; i < Len; i = i + 2, j++)
send[j] = Convert.ToByte(str.Substring(i, 2), 16);
sComm.Write(send, 0, send.Length);
}
//清除空格。
private string DelSpace(string str)
{
string TempStr = string.Empty;
int Len = str.Length;
for (int i = 0; i < Len; i++)
{
if (str[i] != ' ')
TempStr += str[i];
}
//Hex 位数检查。
Len = TempStr.Length;
if (Len % 2 != 0)
TempStr = '0' + TempStr;
return TempStr;
}
//重新打开端口。
private void ReOpenPort()
{
try
{
btClose_Click(null,null);
//重新打开通讯端口。
if (!sComm.IsOpen)
btOpen_Click(null, null);
}
catch (Exception Err)
{
MessageBox.Show(Err.Message, "串口调试助手");
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
foreach (string com in System.IO.Ports.SerialPort.GetPortNames()) //自动获取串行口名称
this.cmPort.Items.Add(com);
cmPort.SelectedIndex = 0;
}
catch
{
MessageBox.Show("找不到通讯端口!", "串口调试助手");
}
}
private void OpenPort()
{
//***避免串口死锁***
sComm.WriteTimeout = 1000; //写超时,如果底层串口驱动效率问题,能有效的避免死锁。
sComm.ReadTimeout = 1000; //读超时,同上。
sComm.NewLine = "\r\n"; //回车换行。
sComm.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.sComm_DataReceived); //注册事件。
//***避免串口死锁***
sComm.PortName = cmPort.Text;
sComm.BaudRate = int.Parse(cmBaudRate.Text);
sComm.DataBits = int.Parse(cmDataBit.Text);
sComm.Parity = (Parity)Enum.Parse(typeof(Parity), cmParity.Text);
sComm.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmStopBit.Text);
sComm.Open();
}
private void ClosePort()
{
//安全关闭当前串口。
//***避免串口死锁***
sComm.DataReceived -= this.sComm_DataReceived; //注销串口中断接收事件,避免下次再执行进来,造成死锁。
while(IsReceving)
Application.DoEvents(); //处理串口接收事件及其它系统消息。
sComm.Close(); //现在没有死锁,可以关闭串口。
//***避免串口死锁***
}
private void StopAutoSend()
{
//停止自动发送字符串。
TimeStr.Stop();
TimeStr.Enabled = false;
tbTimeStr.Enabled = true;
cbTimeStr.Checked = false;
//停止自动发送命令。
TimeHex.Stop();
TimeHex.Enabled = false;
tbTimeHex.Enabled = true;
cbTimeHex.Checked = false;
}
//===================================================
private void btOpen_Click(object sender, EventArgs e)
{
try
{
OpenPort(); //安全打开串口。
if (sComm.IsOpen)
{
btClose.Enabled = true;
btOpen.Enabled = false;
lbComStat.Text = "已打开 " + Convert.ToString(sComm.PortName) + ' ' + Convert.ToString(sComm.BaudRate) + ' ' + Convert.ToString(sComm.DataBits) + ' ' + Convert.ToString(sComm.Parity) + ' ' + Convert.ToString(sComm.StopBits);
tbSendStr.Focus();
}
}
catch (Exception er)
{
StopAutoSend(); //停止自动发送。
ClosePort(); //安全关闭当前串口。
MessageBox.Show("端口打开失败!" + er.Message, "串口调试助手");
lbComStat.Text = "已关闭";
}
}
private void btSend_Click(object sender, EventArgs e)
{
//自动打开端口。
if (!sComm.IsOpen)
btOpen_Click(null, null);
//发送文本。
try
{
string txt = tbSendStr.Text;
Byte[] EncodeByte = new byte[txt.Length * 2];
EncodeByte = Encoding.GetEncoding("GB2312").GetBytes(txt);
int Len = EncodeByte.Length;
sComm.Write(EncodeByte, 0, Len);
}
catch (Exception err)
{
MessageBox.Show(err.Message, "串口调试助手");
}
}
private void btClrSend_Click(object sender, EventArgs e)
{
tbSendStr.Text = string.Empty;
}
private void cmPort_MouseDown(object sender, MouseEventArgs e)
{
try
{
cmPort.Items.Clear();
foreach (string com in System.IO.Ports.SerialPort.GetPortNames()) //自动获取串行口名称
this.cmPort.Items.Add(com);
}
catch
{
MessageBox.Show("找不到通讯端口!", "串口调试助手");
}
}
private void sComm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
IsReceving = true; //***正在接收状态指示。
//读入收到的数据。
int Len = sComm.BytesToRead;
if (Len < 1)
{
IsReceving = false; //***接收完成状态指示。
return;
}
byte[] data = new byte[Len];
sComm.Read(data, 0, Len);
//字符串处理。
string Str = Encoding.GetEncoding("GB2312").GetString(data);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -