0

我正在使用 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();
    }

在串口接收事件中没有收到任何内容。

有什么我做错了吗?

4

1 回答 1

3

让您的其他类定义它自己的事件以供表单处理,该事件可以为表单提供读取的字节:

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
}
于 2013-02-21T15:06:07.263 回答