如何等待COM端口上的数据

时间:2017-06-13 20:38:48

标签: c++ visual-c++ serial-port

我正在使用.Net框架的SerialPort类(System.IO.Ports),我正在尝试等待接收数据。我环顾四周,WaitCommEvent函数似乎是人们建议使用的,但是它希望HANDLE作为第一个参数。我想知道如何从SerialPort获取句柄或者以不同的方式等待与SerialPort类兼容的数据。

1 个答案:

答案 0 :(得分:0)

SerialPort class有一个DataReceived事件:

  

表示已通过SerialPort对象表示的端口接收数据。

该文档提供了以下C ++ / CLI示例:

#using <System.dll>

using namespace System;
using namespace System::IO::Ports;

ref class PortDataReceived
{
public:
    static void Main()
    {
        SerialPort^ mySerialPort = gcnew SerialPort("COM1");

        mySerialPort->BaudRate = 9600;
        mySerialPort->Parity = Parity::None;
        mySerialPort->StopBits = StopBits::One;
        mySerialPort->DataBits = 8;
        mySerialPort->Handshake = Handshake::None;
        mySerialPort->RtsEnable = true;

        mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort->Open();

        Console::WriteLine("Press any key to continue...");
        Console::WriteLine();
        Console::ReadKey();
        mySerialPort->Close();
    }

private:
    static void DataReceivedHandler(
                        Object^ sender,
                        SerialDataReceivedEventArgs^ e)
    {
        SerialPort^ sp = (SerialPort^)sender;
        String^ indata = sp->ReadExisting();
        Console::WriteLine("Data Received:");
        Console::Write(indata);
    }
};

int main()
{
    PortDataReceived::Main();
}