【发布时间】:2013-02-06 22:43:47
【问题描述】:
我正在使用 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();
}
串口收到事件没有收到任何内容。
我做错了什么吗?
【问题讨论】:
-
不要抓到
SystemException。改为捕获Exception。另外,如果您想真正了解发生了什么,请显示ex.ToString() -
您不会从 new SerialPort 对象中读取太多内容。将 sender 转换为 SerialPort 以使用实际生成事件的实例。
标签: c# events event-handling