本程序采用的是DataReceived方法
1 发送字节
字节的转换
bySend[0] = Byte.Parse(textBox1.Text, System.Globalization.NumberStyles.HexNumber);
发送字节
clsComPort.Write(bySend, 0, 1);
2 接收字节
接收事件初始化
clsComPort.DataReceived += new SerialDataReceivedEventHandler(OnDataReceived);
clsComPort.ReceivedBytesThreshold = 1;//门槛是1个字节
该过程中包含步骤:
I 定义委托
II 声明实例
III 传递处理程序句柄参数给委托
源代码如下:
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.VisualBasic;
namespace serialport_CSharp
{
public partial class Form1 : Form
{
SerialPort clsComPort = new SerialPort("COM1",9600,Parity.None,8,StopBits.One);
delegate void dgtSerialPort(byte byString);//定义委托
dgtSerialPort clsInterfaceSerialportHandle;//定义类
byte[] byByteReceive = new byte[1];
public bool bComIsOpen;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//init ComSelected
int i;
for (i = 1; i <= 16;i++ )
{
ComSel.Items.Add("COM" + i);
}
ComSel.SelectedIndex = 0;
//init serialport
clsComPort.Close();
clsComPort.ReceivedBytesThreshold = 1;//门槛是1个字节
clsInterfaceSerialportHandle = new dgtSerialPort(UpdateText);
clsComPort.DataReceived += new SerialDataReceivedEventHandler(OnDataReceived);
//init variable
bComIsOpen = false;
}
private void btnOpenCloseCmd_Click(object sender, EventArgs e)
{
try
{
if (!bComIsOpen) //comport is close
{
clsComPort.PortName = ComSel.SelectedItem.ToString();
clsComPort.Open();
btnComOpenCloseCmd.Text = "关闭串口";
bComIsOpen = true;
}
else
{
clsComPort.Close();
btnComOpenCloseCmd.Text = "打开串口";
bComIsOpen = false;
}
}
catch
{
MessageBox.Show("串口无效","串行通信",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void btnSendCmd_Click(object sender, EventArgs e)
{
if (!bComIsOpen)
{
MessageBox.Show("请打开串口!", "串口通信", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (textBox1.Text=="")
{
MessageBox.Show("请输入字符!", "串口通信", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Byte[] bySend=new byte[1];
bySend[0] = Byte.Parse(textBox1.Text, System.Globalization.NumberStyles.HexNumber);
clsComPort.Write(bySend, 0, 1);
}
}
}
void OnDataReceived(object sender,SerialDataReceivedEventArgs e)
{
clsComPort.Read(byByteReceive, 0, 1);
this.Invoke(clsInterfaceSerialportHandle, byByteReceive[0]);
}
void UpdateText(byte bystr)
{
textBox2.Text = Conversion.Hex(bystr);
}
}
}