我正在使用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();
}
串口接收事件没有收到任何内容。
我有什么问题吗?
答案 0 :(得分:2)
让你的另一个类定义它自己的事件来处理表单,它可以为表单提供读取的字节:
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");
}
}
}
接下来,您不想在SerialPortEvent
中创建Main
实例,您需要在主窗体的构造函数或加载事件中创建它:
public Form1()
{
SerialPortEvent serialPortEvent = new SerialPortEvent();
serialPortEvent.DataReceived += ProcessData;
}
private void ProcessData(byte[] data)
{
//TODO do stuff with data
}