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 Custom Event DataReceived As SerialDataReceivedEventHandler 
Public Event DataReceived As SerialDataReceivedEventHandler 

事件類型

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

備註

資料事件可能是列舉中的任何專案所造成 SerialDataData 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.

DataReceived如果收到 Eof 字元,則也會引發事件,不論內部輸入緩衝區中的位元組數目和屬性的值為何 ReceivedBytesThresholdThe 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.

PinChangedDataReceivedErrorReceived 事件可能會依序呼叫,且當基礎資料流程報告錯誤和執行事件處理常式時,可能會有些微延遲。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.

DataReceived每個收到的位元組都不保證會引發事件。The 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 或中的元素 Form Control ,請使用 post 變更要求 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.

適用於