using System;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;
namespace myUSART
{
public par
tial class Form1 : Form
{
SerialPort sp = new SerialPort();
public Form1()
{
InitializeComponent();
}
// 检测是否有可用串口,有添加到下拉菜单,没有提示失败
private void CheckPort()
{
cbxPortName.Items.Clear(); ///清除数据
bool haveCOM = false; ///默认串口资源标志无串口资源
string[] sn = SerialPort.GetPortNames(); ///获取当前计算机的串行端口名称到字符串数组
if (sn == null) ///获取失败,提示错误(看代码提示信息)
{
haveCOM = false;
}
else ///获取成功,逐个判断串口资源是否可用
{
foreach (string s in sn) ///字符串s获取串行名称端口数组sn的端口名称
{
bool Useful = false; ///默认端口资源不可用
try
{
SerialPort sp = new SerialPort(s); ///获取字符串s的端口名称创建端口对象
sp.Open();
sp.Close();
Useful = true;
}
catch
{
Useful = false;
}
if (Useful) ///若端口名称可用,添加到端口数组集合并设串口资源标志有串口资源
{
cbxPortName.Items.Add(s);
haveCOM = true;
}
}
}
if (haveCOM) ///有串口资源默认显示最后一个端口名称
{
cbxPortName.SelectedIndex = 1; ///默认显示最后一个端口名称
}
else ///没有串口资源提示错误消息
{
MessageBox.Show("Opration SerialPort failed! It's not useful!","Error");
}
}
//初始化串口设置
private void SetSerialPort()
{
try
{
sp.PortName = cbxPortName.Text.Trim();//端口名
sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//波特率
if (cbxStopBits.Text.Trim() == "1")//停止位
{
sp.StopBits = StopBits.One;
}
else if (cbxStopBits.Text.Trim() == "1.5")
{
sp.StopBits = StopBits.OnePointFive;
}
else if (cbxStopBits.Text.Trim() == "2")
{
sp.StopBits = StopBits.Two;
}
else
{
sp.StopBits = StopBits.None;
}
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.ToString().Trim());//数据位
if (cbxParity.Text.Trim() == "奇校验")//奇偶校验位
{
sp.Parity = Parity.Odd;
}
else if (cbxParity.Text.Trim() == "偶校验")
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}
sp.Encoding = Encoding.UTF8;//设置串口
通信的编码格式,默认ASCII
}
catch
{
throw;
}
}
//16进制字符串转换成ASCII字符串
private string HexToASCII(string str)
{
try
{
//去掉字符串首尾的空白后以空格为界线来分割成字符串数组
string[] mystr = str.Trim().Split(' ');
//定义一个和字符串数组等长的字节数组
byte[] t = new byte[mystr.Length];
//将字符串数组的元素转换为字节数组并赋值给字节数组
for (int i = 0; i < t.Length; i++)
{
t
= Convert.ToByte(mystr, 16);
}
//以UTF8编码方式转换字节数组为字符串
return Encoding.UTF8.GetString(t);
}
catch (Exception ex)
{
ckbHexSend.Select();
MessageBox.Show("转换失败!" + ex.Message, "错误提示");
return str;
}
}
//字符串转换成16进制字符
private string ASCIIToHex(string str)
{
try
{
byte[] a = Encoding.UTF8.GetBytes(str.Trim());
string mystr1 = "";
for (int i = 0; i < a.Length; i++)
{
mystr1 += a.ToString("X2") + " ";
}
return mystr1;
}
catch (Exception ex)
{
ckbHexSend.Select();
MessageBox.Show("转换失败!" + ex.Message, "错误提示");
return str;
}
}
//接收串口数据事件
private void COMReceived(object sender,SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
this.Invoke((EventHandler)(delegate {
try
{
byte[] a = new byte[sp.BytesToRead];
sp.Read(a, 0, a.Length);
string mystr2 = Encoding.UTF8.GetString(a);
string b = null;
if (ckbHexShow.Checked)
{
b = HexToASCII(mystr2);
}
else
{
b = mystr2;
}
tbxReceivedData.Text += b;
}
catch
{
throw;
}
}));
}
private void Form1_Load(object sender, EventArgs e)
{
//设置窗口大小
this.MaximizeBox = false;//隐藏最大化按钮
this.MaximumSize = this.Size;//固定窗口尺寸最大为当前尺寸
this.MinimumSize = this.Size;//固定窗口尺寸最小为当前尺寸
tbxSendData.Focus();//默认将光标放在发送文本框上
ckbHexShow.Select();//默认选择ASCII字符显示
ckbHexSend.Select();//默认选择ASCII字符显示
CheckPort();//检测可用串口
//初始化串口设置
cbxBaudRate.SelectedIndex = 0;
cbxStopBits.SelectedIndex = 0;
cbxDataBits.SelectedIndex = 0;
cbxParity.SelectedIndex = 0;
}
private void rbtnOpenCOM_Click(object sender, EventArgs e)
{
if (rbtnOpenCOM.Text == "打开串口")
{
SetSerialPort();//设置串口函数
if (!sp.IsOpen)
{
try
{
sp.Open(); //打开串口
//禁用设置控件
cbxPortName.Enabled = false;
cbxBaudRate.Enabled = false;
cbxParity.Enabled = false;
cbxStopBits.Enabled = false;
cbxDataBits.Enabled = false;
rbtnOpenCOM.Text = "关闭串口";
sp.DataReceived += new SerialDataReceivedEventHandler(COMReceived);//定义串口接收事件
}
catch (Exception ex)
{
MessageBox.Show("串口"/*+cbxPort.Text*/+ "打开失败,失败原因:" + ex.Message, "错误提示");
}
}
}
else //关闭串口
{
if (sp.IsOpen) //判断串口是否打开
{
try
{
sp.Close(); //关闭串口
//启用设置控件
cbxPortName.Enabled = true;
cbxBaudRate.Enabled = true;
cbxParity.Enabled = true;
cbxStopBits.Enabled = true;
cbxDataBits.Enabled = true;
rbtnOpenCOM.Text = "打开串口";
rbtnOpenCOM.Checked = false;
}
catch (Exception ex)
{
MessageBox.Show("串口"/*+ cbxPort.Text*/ + "关闭失败,错误提示:" + ex.Message, "错误提示");
}
}
else
{
cbxPortName.Enabled = true;
cbxBaudRate.Enabled = true;
cbxParity.Enabled = true;
cbxStopBits.Enabled = true;
cbxDataBits.Enabled = true;
rbtnOpenCOM.Text = "打开串口";
MessageBox.Show("串口未打开,无法关闭!", "错误提示");
}
}
}
//选中HEX发送就将字符串数据转换为HEX数据,否则相反
private void ckbHexSend_CheckedChanged(object sender, EventArgs e)
{
if (ckbHexSend.Checked)
{
tbxSendData.Text = ASCIIToHex(tbxSendData.Text.ToString());
}
else
{
tbxSendData.Text = HexToASCII(tbxSendData.Text);
}
}
private void Send_Click(object sender, EventArgs e)
{
try
{
string mystr1 = tbxSendData.Text.Trim();
if (ckbHexSend.Checked)
{
mystr1 = ASCIIToHex(tbxSendData.Text.ToString());
}
byte[] a = Encoding.UTF8.GetBytes(mystr1);
string mystr2 = Encoding.UTF8.GetString(a);
sp.Write(mystr2);
}
catch (Exception ex)
{
MessageBox.Show("请打开串口!", ex.Message);
}
}
//清空接收
private void button2_Click(object sender, EventArgs e)
{
tbxReceivedData.Clear();
}
//清空发送
private void button4_Click(object sender, EventArgs e)
{
tbxSendData.Clear();
}
private void btSaveFiles_Click(object sender, EventArgs e)
{
char[] charData;
byte[] byData;
string s;
try
{
FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
if (cbxPortName.Text == "")
{
s = "No";
}
else
{
s = cbxPortName.Text + "+" + cbxBaudRate.Text;
}
charData = s.ToCharArray();
byData = new byte[charData.Length];
Encoder e1 = Encoding.UTF8.GetEncoder();
e1.GetBytes(charData, 0, charData.Length, byData, 0, true);
aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(byData, 0, charData.Length);
aFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "友情提示");
}
}
private void ckbWordWrap_CheckedChanged(object sender, EventArgs e)
{
}
//选中HEX显示就将字符串数据转换为HEX数据,否则相反
private void ckbHexShow_CheckedChanged(object sender, EventArgs e)
{
if (ckbHexShow.Checked)
{
tbxReceivedData.Text = ASCIIToHex(tbxReceivedData.Text.ToString());
}
else
{
tbxReceivedData.Text = HexToASCII(tbxReceivedData.Text);
}
}
}
}