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 Microsoft.Win32;
namespace PotrTEST
{
public partial class Form1 : Form
{
public SerialPort com = new SerialPort();
//定义端口类
private SerialPort ComDevice = new SerialPort();
public Form1()
{
InitializeComponent();
InitralConfig(int.Parse(comboBox_BaudRate.Text));
}
/// <summary>
/// 从注册表获取系统串口列表
/// </summary>
public string[] GetComList()
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\DeviceMap\SerialComm");
string[] sSubKeys = keyCom.GetValueNames();
string[] str = new string[sSubKeys.Length];
for (int i = 0; i < sSubKeys.Length; i++)
{
str[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return str;
}
/// <summary>
/// 配置初始化
/// </summary>
private void InitralConfig(int btl)
{
Boolean open = false;
string[] coms = GetComList();
for (int i = 0; i < coms.Length; i++)
{
open = false;
if (com.IsOpen)
{
com.Close();
}
comboBox_Port.Items.Add(coms[i]);
}
//向ComDevice.DataReceived(是一个事件)注册一个方法Com_DataReceived,当端口类接收到信息时时会自动调用Com_DataReceived方法
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
/// <summary>
/// 一旦ComDevice.DataReceived事件发生,就将从串口接收到的数据显示到接收端对话框
/// </summary>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//开辟接收缓冲区
byte[] ReDatas = new byte[ComDevice.BytesToRead];
//从串口读取数据
ComDevice.Read(ReDatas, 0, ReDatas.Length);
//实现数据的解码与显示
AddData(ReDatas);
}
/// <summary>
/// 解码过程
/// </summary>
/// <param name="data">串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取</param>
public void AddData(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.AppendFormat("{0:x2}" + " ", data[i]);
}
AddContent(sb.ToString());//.ToUpper()
}
/// <summary>
/// 接收端对话框显示消息
/// </summary>
/// <param name="content"></param>
private void AddContent(string content)
{
BeginInvoke(new MethodInvoker(delegate
{
textBox_Receive.AppendText(content);
}));
}
/// <summary>
/// 串口开关
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_Switch_Click(object sender, EventArgs e)
{
if (comboBox_Port.Items.Count <= 0)
{
MessageBox.Show("未发现可用串口,请检查硬件设备");
return;
}
if (ComDevice.IsOpen == false)
{
//设置串口相关属性
ComDevice.PortName = comboBox_Port.Text;//comboBox_Port.SelectedItem.ToString();
ComDevice.BaudRate = Convert.ToInt32(comboBox_BaudRate.Text);//(comboBox_BaudRate.SelectedItem.ToString());
ComDevice.Parity = (Parity)Convert.ToInt32(comboBox_CheckBits.Text);//(comboBox_CheckBits.SelectedIndex.ToString());
ComDevice.DataBits = Convert.ToInt32(comboBox_DataBits.Text);// (comboBox_DataBits.SelectedItem.ToString());
ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox_StopBits.Text); //(comboBox_StopBits.SelectedItem.ToString());
try
{
//开启串口
ComDevice.Open();
button_Send.Enabled = true;
button_Switch.Text = "关闭";
//while (true)
{
//接收数据
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
try
{
ComDevice.Close();
button_Send.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "串口关闭错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
button_Switch.Text = "开启";
}
comboBox_Port.Enabled = !ComDevice.IsOpen;
comboBox_BaudRate.Enabled = !ComDevice.IsOpen;
comboBox_DataBits.Enabled = !ComDevice.IsOpen;
comboBox_StopBits.Enabled = !ComDevice.IsOpen;
comboBox_CheckBits.Enabled = !ComDevice.IsOpen;
}
/// <summary>
/// 将消息编码并发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_Send_Click(object sender, EventArgs e)
{
//if (textBox_Receive.Text.Length > 0)
//{
// textBox_Receive.AppendText("
");
//}
byte[] sendData = null;
//sendData = Encoding.UTF8.GetBytes(textBox_Receive.Text);
sendData = Hex16StringToHex16Byte(textBox_Receive.Text);
SendData(sendData);
}
/// <summary>
/// 此方法用于将16进制的字符串转换成16进制的字节数组
/// </summary>
/// <param name="_hex16ToString">要转换的16进制的字符串。</param>
public static byte[] Hex16StringToHex16Byte(string _hex16String)
{
//去掉字符串中的空格。
_hex16String = _hex16String.Replace(" ", "");
if (_hex16String.Length / 2 == 0)
{
_hex16String += " ";
}
//声明一个字节数组,其长度等于字符串长度的一半。
byte[] buffer = new byte[_hex16String.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
//为字节数组的元素赋值。
buffer[i] = Convert.ToByte((_hex16String.Substring(i * 2, 2)), 16);
}
//返回字节数组。
return buffer;
}
/// <summary>
/// 此函数将编码后的消息传递给串口
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool SendData(byte[] data)
{
if (ComDevice.IsOpen)
{
try
{
//将消息传递给串口
ComDevice.Write(data, 0, data.Length);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("串口未开启", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
/// <summary>
/// 16进制编码
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private byte[] strToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0) hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
return returnBytes;
}
private void Form1_Load(object sender, EventArgs e)
{
//button_Send.PerformClick();
}
//以下两个指令是结合一款继电器而设计的
//private void button_On_Click(object sender, EventArgs e)
//{
// textBox_Send.Text = "005A540001010000B0";
//}
//private void button_Off_Click(object sender, EventArgs e)
//{
// textBox_Send.Text = "005A540002010000B1";
//}
}
}