SerialPort.DataReceived 事件

定义

指示已通过由 SerialPort 对象表示的端口接收了数据。Indicates that data has been received through a port represented by the SerialPort object.

public:
 event System::IO::Ports::SerialDataReceivedEventHandler ^ DataReceived;
public event System.IO.Ports.SerialDataReceivedEventHandler DataReceived;
member this.DataReceived : System.IO.Ports.SerialDataReceivedEventHandler 
Public Event DataReceived As SerialDataReceivedEventHandler 

示例

此示例将添加SerialDataReceivedEventHandlerDataReceived ,以读取在 COM1 端口上接收到的所有可用数据。This example adds a SerialDataReceivedEventHandler to DataReceived to read all the available data received on the COM1 port. 请注意,若要测试此代码,必须将硬件附加到 COM1,以发送数据。Note that to test this code it is necessary to have hardware attached to COM1 that will send data.

#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();
}
using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new 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 += new 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);
    }
}
Imports System.IO.Ports

Class PortDataReceived
    Public Shared Sub Main()
        Dim mySerialPort As New SerialPort("COM1")

        mySerialPort.BaudRate = 9600
        mySerialPort.Parity = Parity.None
        mySerialPort.StopBits = StopBits.One
        mySerialPort.DataBits = 8
        mySerialPort.Handshake = Handshake.None
        mySerialPort.RtsEnable = True

        AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler

        mySerialPort.Open()

        Console.WriteLine("Press any key to continue...")
        Console.WriteLine()
        Console.ReadKey()
        mySerialPort.Close()
    End Sub

    Private Shared Sub DataReceivedHandler(
                        sender As Object,
                        e As SerialDataReceivedEventArgs)
        Dim sp As SerialPort = CType(sender, SerialPort)
        Dim indata As String = sp.ReadExisting()
        Console.WriteLine("Data Received:")
        Console.Write(indata)
    End Sub
End Class

注解

数据事件可能由SerialData枚举中的任何项导致。Data events can be caused by any of the items in the SerialData enumeration. 由于操作系统确定是否引发此事件,因此不会报告所有奇偶校验错误。Because the operating system determines whether to raise this event or not, not all parity errors may be reported.

如果收到 Eof 字符,则会引发ReceivedBytesThreshold 事件,而不考虑内部输入缓冲区中的字节数和属性的值。DataReceivedThe DataReceived event is also raised if an Eof character is received, regardless of the number of bytes in the internal input buffer and the value of the ReceivedBytesThreshold property.

PinChanged可以DataReceived按顺序ErrorReceived调用、和事件,并且基础流报告错误和执行事件处理程序之间可能会有轻微的延迟。PinChanged, DataReceived, and ErrorReceived events may be called out of order, and there may be a slight delay between when the underlying stream reports the error and when the event handler is executed. 一次只能执行一个事件处理程序。Only one event handler can execute at a time.

不保证为每个接收的字节引发事件。DataReceivedThe DataReceived event is not guaranteed to be raised for every byte received. BytesToRead使用属性可以确定要在缓冲区中读取的数据量。Use the BytesToRead property to determine how much data is left to be read in the buffer.

从对象接收数据时, DataReceived在辅助线程上引发事件。 SerialPortThe DataReceived event is raised on a secondary thread when data is received from the SerialPort object. 由于此事件是在辅助线程上引发的,而不是在主线程上引发的,因此尝试修改主线程中的某些元素(如 UI 元素)可能会引发线程异常。Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. 如果需要修改 main FormControl中的元素,请使用Invoke将更改请求回发,这会在适当的线程上完成工作。If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

有关处理事件的详细信息, 请参阅处理和引发事件For more information about handling events, see Handling and Raising Events.

适用于