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.

DataReceived イベントは、内部入力バッファーのバイト数と ReceivedBytesThreshold プロパティの値に関係なく、Eof 文字が受信された場合にも発生します。The 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.

PinChangedDataReceived、および 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. 一度に実行できるイベントハンドラーは1つだけです。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.

SerialPort オブジェクトからデータを受信すると、セカンダリスレッドで DataReceived イベントが発生します。The 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. メイン Form または Control内の要素を変更する必要がある場合は、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.

適用対象