using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormSeriport
{
public partial class FORM1 : Form
{
SerialPort sp = new SerialPort();
public FORM1()
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
sp.Close();
lbl_TxRx.Text = "Tx:" +0+" " + "Rx:" + 0;
}
private void Form1_Load_1(object sender, EventArgs e)
{
Timer_SendDate.Interval = 1000;
Timer_SendDate.Stop();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
lbl_Move.Text = e.X.ToString() + " " + e.Y.ToString();
}
private void serialPort1_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
MessageBox.Show("接收数据时发生未知错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btn_OpenSerial_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
btn_OpenSerial.Text = "开启串口";
try
{
sp.PortName = comboBox_Com.Text;
sp.BaudRate = Convert.ToInt32(comboBox_Bot.Text);
sp.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), comboBox_Parity.Text);
sp.DataBits = Convert.ToInt16(comboBox_DateBit.Text);
sp.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), comboBox_StopBit.Text);
sp.Encoding = Encoding.Default; //设置串口编码为default:获取操作系统的当前 ANSI 代码页的编码。
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
sp.Open(); //开启串口
if (checkBox_ClearShow.Checked) //如果开启了自动清空功能
Timer_SendDate.Start();
btn_OpenSerial.Text = "关闭串口";
}
catch
{
MessageBox.Show("配置串口出错,检查各项参数是否设置!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
btn_OpenSerial.Text = "关闭串口";
try
{
sp.Close();
btn_OpenSerial.Text = "开启串口";
MessageBox.Show("串口已关闭!","提示",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("出现未知错误,串口关闭失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
string receiveData;
UInt32 receiveBytesCount;
string sendData;
UInt32 sendBytesCount;
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
receiveData = sp.ReadExisting();
receiveBytesCount += (UInt32)receiveData.Length;
//字符串显示
if (checkBox_ClearShow.Checked == false)
{
if (checkBox_16Show.Checked == false) //hex 方式显示
{
richtxtbox_ShowGetNumber.AppendText(receiveData);
richtxtbox_ShowGetNumber.Focus(); //让光标到这来
richtxtbox_ShowGetNumber.Select(richtxtbox_ShowGetNumber.TextLength, 0);
this.richtxtbox_ShowGetNumber.ScrollToCaret(); //设置光标到最后
}
//16进制显示
else
{
byte[] recData = System.Text.Encoding.Default.GetBytes(receiveData);// 将接受到的字符串据转化成数组;
foreach (byte str in recData)
{
richtxtbox_ShowGetNumber.AppendText(string.Format("{0:X2} ", str));
}
}
}
lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();
}
private void btn_GetCom_Click(object sender, EventArgs e) //自动获取串口号
{
string[] serialPortName = System.IO.Ports.SerialPort.GetPortNames();
foreach (string name in serialPortName)
{
comboBox_Com.Text = name;
}
}
private void btn_Send_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
btn_OpenSerial.Text = "开启串口";
MessageBox.Show("请打开串口!", "错误",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
btn_OpenSerial.Text = "关闭串口";
if (checkBox_SendByItself.Checked)
{
Timer_SendDate.Interval = Convert.ToInt32(textBox_SendTime.Text);
Timer_SendDate.Start();
}
sendData = richTextBox_Send.Text;
if (checkBox_SendIn16.Checked == false)
{
sp.Write(sendData);
}
else
{
try
{
sendData.Replace("0x", ""); //去掉0x
sendData.Replace("0X", ""); //去掉0X
// sendData.
string[] strArray = sendData.Split(new char[] { ',', ',', '\r', '\n', ' ', '\t' });
int decNum = 0;
int i = 0;
byte[] sendBuffer = new byte[strArray.Length]; //发送数据缓冲区
foreach (string str in strArray)
{
try
{
decNum = Convert.ToInt16(str, 16);
sendBuffer[i] = Convert.ToByte(decNum);
i++;
}
catch
{
}
}
sp.Write(sendBuffer, 0, sendBuffer.Length);
//更新发送数据计数
sendBytesCount += (UInt32)sendBuffer.Length;
lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();
}
catch
{
}
}
}
}
private void Timer_SendDate_Tick(object sender, EventArgs e)
{
if (checkBox_ClearShow.Checked)
richtxtbox_ShowGetNumber.Text = null;
sendData = richTextBox_Send.Text;
if (sp.IsOpen)
{
btn_OpenSerial.Text = "关闭串口";
if (checkBox_SendByItself.Checked)
{
if (checkBox_SendIn16.Checked == false)
{
sp.Write(sendData);
}
else
{
try
{
sendData.Replace("0x", ""); //去掉0x
sendData.Replace("0X", ""); //去掉0X
// sendData.
string[] strArray = sendData.Split(new char[] { ',', ',', '\r', '\n', ' ', '\t' });
int decNum = 0;
int i = 0;
byte[] sendBuffer = new byte[strArray.Length]; //发送数据缓冲区
foreach (string str in strArray)
{
try
{
decNum = Convert.ToInt16(str, 16);
sendBuffer[i] = Convert.ToByte(decNum);
i++;
}
catch
{
}
}
sp.Write(sendBuffer, 0, sendBuffer.Length);
}
catch
{
}
}
//更新发送数据计数
sendBytesCount += (UInt32)sendData.Length;
lbl_TxRx.Text = "Tx:" + sendBytesCount.ToString()+" " + "Rx:" + receiveBytesCount.ToString();
}
else
{
if (checkBox_ClearShow.Checked)
checkBox_SendByItself.CheckState=CheckState .Unchecked ;
else
Timer_SendDate.Stop();
}
}
else
{
btn_OpenSerial.Text = "开启串口";
Timer_SendDate.Stop();
MessageBox.Show("串口已经关闭!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btn_ClearAll_Click(object sender, EventArgs e)
{
richtxtbox_ShowGetNumber.Text = null;
richTextBox_Send.Text = null;
}
}
}