效果图:
====================== 代码段 =================================
public partial class SerialPortEx : Form
{
private SerialPort sp = new SerialPort();
bool isOpen = false; //
bool isSetProperty = false; //属性设置标志
bool isHex = false; //十六进制显示标志
bool isFileOpen = false;
string RecvDataText = null;
public SerialPortEx()
{
InitializeComponent();
}
private void SerialPort_Load(object sender, EventArgs e) //串口列表
{
for (int i = 0; i < 6; i++)
{
cbxComPort.Items.Add("COM" + (i + 1).ToString());
}
cbxComPort.SelectedIndex = 0; //设置串口初始值
//列出常用的波特率表
cbxBaudRate.Items.Add("1200");
cbxBaudRate.Items.Add("2400");
cbxBaudRate.Items.Add("4800");
cbxBaudRate.Items.Add("9600");
cbxBaudRate.Items.Add("19200");
cbxBaudRate.Items.Add("38400");
cbxBaudRate.SelectedIndex = 5;
//列出停止位
cbxStopBits.Items.Add("0");
cbxStopBits.Items.Add("1");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("2");
cbxStopBits.SelectedIndex = 1;
//列出数据位
cbxDataBits.Items.Add("8");
cbxDataBits.Items.Add("7");
cbxDataBits.Items.Add("6");
cbxDataBits.Items.Add("5");
cbxDataBits.SelectedIndex = 1;
//列出奇偶校验位
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = 0;
//默认char显示
rbnChar.Checked = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnCheckCom_Click(object sender, EventArgs e) //检测Com口
{
bool comExist = false;
cbxComPort.Items.Clear();
for (int i = 0; i < 10; i++)
{
try
{
SerialPort sp = new SerialPort("COM" + (i + 1).ToString());
sp.Open();
sp.Close();
cbxComPort.Items.Add("COM" + (i + 1).ToString());
comExist = true;
}
catch (Exception)
{
continue;
}
}
if (comExist)
{
cbxComPort.SelectedIndex = 0; //默认第一个
}
else
{
MessageBox.Show("没有找到任何可用串口", "错误提示");
}
}
//串口检测 界面初始化
private bool CheckPortSetting() //检测串口是否初始化
{
if (cbxComPort.Text.Trim() == "") return false;
if (cbxBaudRate.Text.Trim() == "") return false;
if (cbxDataBits.Text.Trim() == "") return false;
if (cbxParity.Text.Trim() == "") return false;
if (cbxStopBits.Text.Trim() == "") return false;
return true;
}
private bool CheckSendDate() //检测发送数据是否为空
{
if (tbxSentData.Text.Trim() == "") return false;
return true;
}
private void SetPortProperty() //
{
sp = new SerialPort();
sp.PortName = cbxComPort.Text.Trim(); //设置串口名
sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim()); //设置串口波特率
int f = (int)Convert.ToSingle(cbxStopBits.Text.Trim()) * 10; //设置停止位
switch (f)
{
case 0:
sp.StopBits = StopBits.None;
break;
case 10:
sp.StopBits = StopBits.One;
break;
case 15:
sp.StopBits = StopBits.OnePointFive;
break;
case 20:
sp.StopBits = StopBits.Two;
break;
default:
sp.StopBits = StopBits.None;
break;
}
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim()); //设置数据位
string parityType = cbxParity.Text.Trim(); //设置奇偶校验
switch (parityType)
{
case "无":
sp.Parity = Parity.None;
break;
case "奇校验":
sp.Parity = Parity.Odd;
break;
case "偶校验":
sp.Parity = Parity.Even;
break;
default:
sp.Parity = Parity.None;
break;
}
sp.ReadTimeout = -1; //超时读取时间
sp.RtsEnable = true; // 指示本设备准备好可接收数据
//定义Data Received事件,当串口收到数据后出发事件
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void btnOpenCom_Click(object sender, EventArgs e)
{
if (isOpen == false)
{
if (!CheckPortSetting()) //检测串口设置
{
MessageBox.Show("串口未设置", "错误提示");
return;
}
if (isSetProperty == false) // 检测
{
SetPortProperty();
isSetProperty = true;
}
try //打开串口
{
sp.Open();
isOpen = true;
btnOpenCom.Text = "关闭串口";
//串口打开后相关的串口设置按钮不再可选择
cbxBaudRate.Enabled = false;
cbxComPort.Enabled = false;
cbxDataBits.Enabled = false;
cbxParity.Enabled = false;
cbxStopBits.Enabled = false;
}
catch (Exception)
{ //失败后设置
isSetProperty = false;
isOpen = false;
MessageBox.Show("串口无效或已经被占用!", "错误提示");
}
}
else
{
sp.Close();
isOpen = false;
isSetProperty = false;
btnOpenCom.Text = "打开串口";
//重置选择按钮有效
cbxBaudRate.Enabled = true;
cbxComPort.Enabled = true;
cbxDataBits.Enabled = true;
cbxParity.Enabled = true;
cbxStopBits.Enabled = true;
}
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
byte[] writeBytes = utf8.GetBytes(tbxSentData.Text);
//byte[] writeBytes11 = new Byte[data1.length]; //
sp.Write(writeBytes,0,writeBytes.Length); //发送数据内容
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
return;
}
}
private void sp_DataReceived(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(100); //延迟100ms等待接收完成数据
this.Invoke((EventHandler)(
delegate {
if (isHex == false)
{
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();// 显示汉字与字符
Byte[] readBytes = new Byte[sp.BytesToRead];
sp.Read(readBytes, 0, readBytes.Length);
string decodedString = utf8.GetString(readBytes);
tbxRecvData.Text += decodedString;
}
else
{
}
}
));
}
}
===========================================================
未完待续:
添加接收信息换行,中文字符处理....
来源:oschina
链接:https://my.oschina.net/u/4274516/blog/3522209