串行端口数据接收事件在表单的单独类中
本文关键字:表单 单独类 事件 数据 串行端口 | 更新日期: 2023-09-27 18:00:28
我使用windows应用程序窗体从串行端口接收数据。在窗体内,我可以引发SerialportDataReceived
事件。但我想要的是将串行端口事件放在一个单独的类中,并将数据返回到表单中
以下是包含串行端口接收数据的eventhandler
的类:
class SerialPortEvent
{
public void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = new SerialPort();
//no. of data at the port
int ByteToRead = sp.BytesToRead;
//create array to store buffer data
byte[] inputData = new byte[ByteToRead];
//read the data and store
sp.Read(inputData, 0, ByteToRead);
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message, "Data Received Event");
}
}
}
收到数据时,如何将此类链接到表单?我必须在主程序中还是在表单中提出事件?
我现在调用的方式主要如下:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
SerialPort mySerialPort = new SerialPort("COM81");
SerialPortEvent ReceivedData = new SerialPortEvent();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(ReceivedData.mySerialPort_DataReceived);
myserialPort.open();
}
串行端口接收事件没有接收到任何内容。
我做错了什么吗?
让另一个类为表单定义自己的事件,以便处理该事件,该事件可以为表单提供读取的字节:
class SerialPortEvent
{
private SerialPort mySerialPort;
public Action<byte[]> DataReceived;
//Created the actual serial port in the constructor here,
//as it makes more sense than having the caller need to do it.
//you'll also need access to it in the event handler to read the data
public SerialPortEvent()
{
mySerialPort = new SerialPort("COM81");
mySerialPort.DataReceived += mySerialPort_DataReceived
myserialPort.open();
}
public void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
//no. of data at the port
int ByteToRead = mySerialPort.BytesToRead;
//create array to store buffer data
byte[] inputData = new byte[ByteToRead];
//read the data and store
mySerialPort.Read(inputData, 0, ByteToRead);
var copy = DataReceived;
if(copy != null) copy(inputData);
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message, "Data Received Event");
}
}
}
接下来,您不希望在Main
中创建SerialPortEvent
实例,而是希望在主窗体的构造函数或加载事件中创建它:
public Form1()
{
SerialPortEvent serialPortEvent = new SerialPortEvent();
serialPortEvent.DataReceived += ProcessData;
}
private void ProcessData(byte[] data)
{
//TODO do stuff with data
}