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 に答える