SerialPort SerialPort SerialPort SerialPort Class

Definición

Representa un recurso de puerto serie.Represents a serial port resource.

public ref class SerialPort : System::ComponentModel::Component
public class SerialPort : System.ComponentModel.Component
type SerialPort = class
    inherit Component
Public Class SerialPort
Inherits Component
Herencia

Ejemplos

En el ejemplo de código siguiente se muestra el uso de la SerialPort clase para permitir a los dos usuarios chat de dos equipos independientes conectados mediante un cable de módem nulo.The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate computers connected by a null modem cable. En este ejemplo, los usuarios se le solicitará un nombre de usuario y la configuración de puerto antes de la charla.In this example, the users are prompted for the port settings and a username before chatting. Ambos equipos deben estar ejecutando el programa para lograr una funcionalidad completa de este ejemplo.Both computers must be executing the program to achieve full functionality of this example.

#using <System.dll>

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

public ref class PortChat
{
private:
    static bool _continue;
    static SerialPort^ _serialPort;

public:
    static void Main()
    {
        String^ name;
        String^ message;
        StringComparer^ stringComparer = StringComparer::OrdinalIgnoreCase;
        Thread^ readThread = gcnew Thread(gcnew ThreadStart(PortChat::Read));

        // Create a new SerialPort object with default settings.
        _serialPort = gcnew SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort->PortName = SetPortName(_serialPort->PortName);
        _serialPort->BaudRate = SetPortBaudRate(_serialPort->BaudRate);
        _serialPort->Parity = SetPortParity(_serialPort->Parity);
        _serialPort->DataBits = SetPortDataBits(_serialPort->DataBits);
        _serialPort->StopBits = SetPortStopBits(_serialPort->StopBits);
        _serialPort->Handshake = SetPortHandshake(_serialPort->Handshake);

        // Set the read/write timeouts
        _serialPort->ReadTimeout = 500;
        _serialPort->WriteTimeout = 500;

        _serialPort->Open();
        _continue = true;
        readThread->Start();

        Console::Write("Name: ");
        name = Console::ReadLine();

        Console::WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console::ReadLine();

            if (stringComparer->Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort->WriteLine(
                    String::Format("<{0}>: {1}", name, message) );
            }
        }

        readThread->Join();
        _serialPort->Close();
    }

    static void Read()
    {
        while (_continue)
        {
            try
            {
                String^ message = _serialPort->ReadLine();
                Console::WriteLine(message);
            }
            catch (TimeoutException ^) { }
        }
    }

    static String^ SetPortName(String^ defaultPortName)
    {
        String^ portName;

        Console::WriteLine("Available Ports:");
        for each (String^ s in SerialPort::GetPortNames())
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Enter COM port value (Default: {0}): ", defaultPortName);
        portName = Console::ReadLine();

        if (portName == "")
        {
            portName = defaultPortName;
        }
        return portName;
    }

    static Int32 SetPortBaudRate(Int32 defaultPortBaudRate)
    {
        String^ baudRate;

        Console::Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
        baudRate = Console::ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return Int32::Parse(baudRate);
    }

    static Parity SetPortParity(Parity defaultPortParity)
    {
        String^ parity;

        Console::WriteLine("Available Parity options:");
        for each (String^ s in Enum::GetNames(Parity::typeid))
        {
            Console::WriteLine("   {0}", s);
        }
		
        Console::Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString());
        parity = Console::ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum::Parse(Parity::typeid, parity);
    }

    static Int32 SetPortDataBits(Int32 defaultPortDataBits)
    {
        String^ dataBits;

        Console::Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
        dataBits = Console::ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return Int32::Parse(dataBits);
    }

    static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        String^ stopBits;

        Console::WriteLine("Available Stop Bits options:");
        for each (String^ s in Enum::GetNames(StopBits::typeid))
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Enter StopBits value (None is not supported and \n" +
            "raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
        stopBits = Console::ReadLine();

        if (stopBits == "")
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum::Parse(StopBits::typeid, stopBits);
    }

    static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        String^ handshake;

        Console::WriteLine("Available Handshake options:");
        for each (String^ s in Enum::GetNames(Handshake::typeid))
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
        handshake = Console::ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum::Parse(Handshake::typeid, handshake);
    }
};

int main()
{
    PortChat::Main();
}
// Use this code inside a project created with the Visual C# > Windows Desktop > Console Application template.
// Replace the code in Program.cs with this code.

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }

    // Display Port values and prompt user to enter a port.
    public static string SetPortName(string defaultPortName)
    {
        string portName;

        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
        portName = Console.ReadLine();

        if (portName == "" || !(portName.ToLower()).StartsWith("com"))
        {
            portName = defaultPortName;
        }
        return portName;
    }
    // Display BaudRate values and prompt user to enter a value.
    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return int.Parse(baudRate);
    }

    // Display PortParity values and prompt user to enter a value.
    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), true);
        parity = Console.ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum.Parse(typeof(Parity), parity, true);
    }
    // Display DataBits values and prompt user to enter a value.
    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return int.Parse(dataBits.ToUpperInvariant());
    }

    // Display StopBits values and prompt user to enter a value.
    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        Console.WriteLine("Available StopBits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter StopBits value (None is not supported and \n" +
         "raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();
       
        if (stopBits == "" )
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
    }
    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
    }
}
' Use this code inside a project created with the Visual Basic > Windows Desktop > Console Application template.
' Replace the default code in Module1.vb with this code. Then right click the project in Solution Explorer,
' select Properties, and set the Startup Object to PortChat.

Imports System.IO.Ports
Imports System.Threading

Public Class PortChat
    Shared _continue As Boolean
    Shared _serialPort As SerialPort

    Public Shared Sub Main()
        Dim name As String
        Dim message As String
        Dim stringComparer__1 As StringComparer = StringComparer.OrdinalIgnoreCase
        Dim readThread As New Thread(AddressOf Read)

        ' Create a new SerialPort object with default settings.
        _serialPort = New SerialPort()

        ' Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName)
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate)
        _serialPort.Parity = SetPortParity(_serialPort.Parity)
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits)
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits)
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake)

        ' Set the read/write timeouts
        _serialPort.ReadTimeout = 500
        _serialPort.WriteTimeout = 500

        _serialPort.Open()
        _continue = True
        readThread.Start()

        Console.Write("Name: ")
        name = Console.ReadLine()

        Console.WriteLine("Type QUIT to exit")

        While _continue
            message = Console.ReadLine()

            If stringComparer__1.Equals("quit", message) Then
                _continue = False
            Else
                _serialPort.WriteLine([String].Format("<{0}>: {1}", name, message))
            End If
        End While

        readThread.Join()
        _serialPort.Close()
    End Sub

    Public Shared Sub Read()
        While _continue
            Try
                Dim message As String = _serialPort.ReadLine()
                Console.WriteLine(message)
            Catch generatedExceptionName As TimeoutException
            End Try
        End While
    End Sub

    ' Display Port values and prompt user to enter a port.
    Public Shared Function SetPortName(defaultPortName As String) As String
        Dim portName As String

        Console.WriteLine("Available Ports:")
        For Each s As String In SerialPort.GetPortNames()
            Console.WriteLine("   {0}", s)
        Next

        Console.Write("Enter COM port value (Default: {0}): ", defaultPortName)
        portName = Console.ReadLine()

        If portName = "" OrElse Not (portName.ToLower()).StartsWith("com") Then
            portName = defaultPortName
        End If
        Return portName
    End Function
    ' Display BaudRate values and prompt user to enter a value.
    Public Shared Function SetPortBaudRate(defaultPortBaudRate As Integer) As Integer
        Dim baudRate As String

        Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate)
        baudRate = Console.ReadLine()

        If baudRate = "" Then
            baudRate = defaultPortBaudRate.ToString()
        End If

        Return Integer.Parse(baudRate)
    End Function

    ' Display PortParity values and prompt user to enter a value.
    Public Shared Function SetPortParity(defaultPortParity As Parity) As Parity
        Dim parity As String

        Console.WriteLine("Available Parity options:")
        For Each s As String In [Enum].GetNames(GetType(Parity))
            Console.WriteLine("   {0}", s)
        Next

        Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), True)
        parity = Console.ReadLine()

        If parity = "" Then
            parity = defaultPortParity.ToString()
        End If

        Return CType([Enum].Parse(GetType(Parity), parity, True), Parity)
    End Function
    ' Display DataBits values and prompt user to enter a value.
    Public Shared Function SetPortDataBits(defaultPortDataBits As Integer) As Integer
        Dim dataBits As String

        Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits)
        dataBits = Console.ReadLine()

        If dataBits = "" Then
            dataBits = defaultPortDataBits.ToString()
        End If

        Return Integer.Parse(dataBits.ToUpperInvariant())
    End Function
    ' Display StopBits values and prompt user to enter a value.

    Public Shared Function SetPortStopBits(defaultPortStopBits As StopBits) As StopBits
        Dim stopBits As String

        Console.WriteLine("Available StopBits options:")
        For Each s As String In [Enum].GetNames(GetType(StopBits))
            Console.WriteLine("   {0}", s)
        Next

        Console.Write("Enter StopBits value (None is not supported and " &
                      vbLf & "raises an ArgumentOutOfRangeException. " &
                      vbLf & " (Default: {0}):", defaultPortStopBits.ToString())
        stopBits = Console.ReadLine()

        If stopBits = "" Then
            stopBits = defaultPortStopBits.ToString()
        End If

        Return CType([Enum].Parse(GetType(StopBits), stopBits, True), StopBits)
    End Function
    Public Shared Function SetPortHandshake(defaultPortHandshake As Handshake) As Handshake
        Dim handshake As String

        Console.WriteLine("Available Handshake options:")
        For Each s As String In [Enum].GetNames(GetType(Handshake))
            Console.WriteLine("   {0}", s)
        Next

        Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString())
        handshake = Console.ReadLine()

        If handshake = "" Then
            handshake = defaultPortHandshake.ToString()
        End If

        Return CType([Enum].Parse(GetType(Handshake), handshake, True), Handshake)
    End Function
End Class

Comentarios

Utilice esta clase para controlar un recurso de archivos de puerto serie.Use this class to control a serial port file resource. Esta clase proporciona E/S sincrónica y orientada a eventos, acceso a los Estados de conexión e interrupción y acceso a las propiedades del controlador serie.This class provides synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. Además, la funcionalidad de esta clase puede colocarse en una instancia interna Stream objeto, accesible a través de la BaseStream propiedad y se pasa a las clases que ajustan o utilizan secuencias.Additionally, the functionality of this class can be wrapped in an internal Stream object, accessible through the BaseStream property, and passed to classes that wrap or use streams.

El SerialPort clase admite las codificaciones siguientes: ASCIIEncoding, UTF8Encoding, UnicodeEncoding, UTF32Encodingy cualquier codificación definida en mscorlib.dll donde la página de códigos es menor que 50000 o la página de códigos es 54936.The SerialPort class supports the following encodings: ASCIIEncoding, UTF8Encoding, UnicodeEncoding, UTF32Encoding, and any encoding defined in mscorlib.dll where the code page is less than 50000 or the code page is 54936. Puede utilizar codificaciones alternativas, pero debe usar el ReadByte o Write método y realizar la codificación por sí mismo.You can use alternate encodings, but you must use the ReadByte or Write method and perform the encoding yourself.

Usa el GetPortNames método para recuperar los puertos válidos para el equipo actual.You use the GetPortNames method to retrieve the valid ports for the current computer.

Si un SerialPort objeto queda bloqueado durante una operación de lectura, no anular el subproceso.If a SerialPort object becomes blocked during a read operation, do not abort the thread. En su lugar, cierre la base de transmitir o desechar la SerialPort objeto.Instead, either close the base stream or dispose of the SerialPort object.

Constructores

SerialPort() SerialPort() SerialPort() SerialPort()

Inicializa una nueva instancia de la clase SerialPort.Initializes a new instance of the SerialPort class.

SerialPort(IContainer) SerialPort(IContainer) SerialPort(IContainer) SerialPort(IContainer)

Inicializa una nueva instancia de la clase SerialPort utilizando el objeto IContainer especificado.Initializes a new instance of the SerialPort class using the specified IContainer object.

SerialPort(String) SerialPort(String) SerialPort(String) SerialPort(String)

Inicializa una instancia nueva de la clase SerialPort utilizando el nombre de puerto especificado.Initializes a new instance of the SerialPort class using the specified port name.

SerialPort(String, Int32) SerialPort(String, Int32) SerialPort(String, Int32) SerialPort(String, Int32)

Inicializa una instancia nueva de la clase SerialPort utilizando el nombre de puerto y la velocidad en baudios especificados.Initializes a new instance of the SerialPort class using the specified port name and baud rate.

SerialPort(String, Int32, Parity) SerialPort(String, Int32, Parity) SerialPort(String, Int32, Parity) SerialPort(String, Int32, Parity)

Inicializa una instancia nueva de la clase SerialPort utilizando el nombre del puerto, la velocidad en baudios y el bit de paridad especificados.Initializes a new instance of the SerialPort class using the specified port name, baud rate, and parity bit.

SerialPort(String, Int32, Parity, Int32) SerialPort(String, Int32, Parity, Int32) SerialPort(String, Int32, Parity, Int32) SerialPort(String, Int32, Parity, Int32)

Inicializa una instancia nueva de la clase SerialPort utilizando el nombre del puerto, la velocidad en baudios, el bit de paridad y los bits de datos especificados.Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, and data bits.

SerialPort(String, Int32, Parity, Int32, StopBits) SerialPort(String, Int32, Parity, Int32, StopBits) SerialPort(String, Int32, Parity, Int32, StopBits) SerialPort(String, Int32, Parity, Int32, StopBits)

Inicializa una instancia nueva de la clase SerialPort utilizando el nombre del puerto, la velocidad en baudios, el bit de paridad, los bits de datos y el bit de parada especificados.Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, data bits, and stop bit.

Campos

InfiniteTimeout InfiniteTimeout InfiniteTimeout InfiniteTimeout

Indica que no se debe agotar el tiempo de espera.Indicates that no time-out should occur.

Propiedades

BaseStream BaseStream BaseStream BaseStream

Obtiene el objeto Stream subyacente para un objeto SerialPort.Gets the underlying Stream object for a SerialPort object.

BaudRate BaudRate BaudRate BaudRate

Obtiene o establece la velocidad en baudios del puerto serie.Gets or sets the serial baud rate.

BreakState BreakState BreakState BreakState

Obtiene o establece el estado de la señal de interrupción.Gets or sets the break signal state.

BytesToRead BytesToRead BytesToRead BytesToRead

Obtiene el número de bytes de datos en el búfer de recepción.Gets the number of bytes of data in the receive buffer.

BytesToWrite BytesToWrite BytesToWrite BytesToWrite

Obtiene el número de bytes de datos en el búfer de envío.Gets the number of bytes of data in the send buffer.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CDHolding CDHolding CDHolding CDHolding

Obtiene el estado de la línea de detección de portadora para el puerto.Gets the state of the Carrier Detect line for the port.

Container Container Container Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Inherited from Component)
CtsHolding CtsHolding CtsHolding CtsHolding

Obtiene el estado de la línea Listo para enviar.Gets the state of the Clear-to-Send line.

DataBits DataBits DataBits DataBits

Obtiene o establece la longitud estándar de los bits de datos por byte.Gets or sets the standard length of data bits per byte.

DesignMode DesignMode DesignMode DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
DiscardNull DiscardNull DiscardNull DiscardNull

Obtiene o establece un valor que indica si no se tienen en cuenta los bytes nulos en las transmisiones entre el puerto y el búfer de recepción.Gets or sets a value indicating whether null bytes are ignored when transmitted between the port and the receive buffer.

DsrHolding DsrHolding DsrHolding DsrHolding

Obtiene el estado de la señal Conjunto de datos preparado (DSR).Gets the state of the Data Set Ready (DSR) signal.

DtrEnable DtrEnable DtrEnable DtrEnable

Obtiene o establece un valor que habilita la señal Terminal de datos preparado (DTR) durante la comunicación en serie.Gets or sets a value that enables the Data Terminal Ready (DTR) signal during serial communication.

Encoding Encoding Encoding Encoding

Obtiene o establece la codificación de bytes para la conversión de texto previa y posterior a la transmisión.Gets or sets the byte encoding for pre- and post-transmission conversion of text.

Events Events Events Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Handshake Handshake Handshake Handshake

Obtiene o establece el protocolo de enlace para la transmisión de datos a través del puerto serie desde Handshake.Gets or sets the handshaking protocol for serial port transmission of data using a value from Handshake.

IsOpen IsOpen IsOpen IsOpen

Obtiene un valor que indica el estado abierto o cerrado del objeto SerialPort.Gets a value indicating the open or closed status of the SerialPort object.

NewLine NewLine NewLine NewLine

Obtiene o establece el valor utilizado para interpretar el final de una llamada a los métodos ReadLine() y WriteLine(String).Gets or sets the value used to interpret the end of a call to the ReadLine() and WriteLine(String) methods.

Parity Parity Parity Parity

Obtiene o establece el protocolo de comprobación de la paridad.Gets or sets the parity-checking protocol.

ParityReplace ParityReplace ParityReplace ParityReplace

Obtiene o establece el byte que reemplaza los bytes no válidos en una secuencia de datos cuando se produce un error de paridad.Gets or sets the byte that replaces invalid bytes in a data stream when a parity error occurs.

PortName PortName PortName PortName

Obtiene o establece el puerto de comunicaciones, incluidos por lo menos todos los puertos COM disponibles.Gets or sets the port for communications, including but not limited to all available COM ports.

ReadBufferSize ReadBufferSize ReadBufferSize ReadBufferSize

Obtiene o establece el tamaño del búfer de entrada de SerialPort.Gets or sets the size of the SerialPort input buffer.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

Obtiene o establece el número de milisegundos que transcurren antes de que se agote el tiempo de espera si una operación de lectura no finaliza.Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.

ReceivedBytesThreshold ReceivedBytesThreshold ReceivedBytesThreshold ReceivedBytesThreshold

Obtiene o establece el número de bytes en el búfer de entrada interno antes de que ocurra un evento DataReceived.Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs.

RtsEnable RtsEnable RtsEnable RtsEnable

Obtiene o establece un valor que indica si la señal Solicitud de envío (RTS) está habilitada durante la comunicación en serie.Gets or sets a value indicating whether the Request to Send (RTS) signal is enabled during serial communication.

Site Site Site Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Inherited from Component)
StopBits StopBits StopBits StopBits

Obtiene o establece el número estándar de bits de parada por byte.Gets or sets the standard number of stopbits per byte.

WriteBufferSize WriteBufferSize WriteBufferSize WriteBufferSize

Obtiene o establece el tamaño del búfer de salida del puerto serie.Gets or sets the size of the serial port output buffer.

WriteTimeout WriteTimeout WriteTimeout WriteTimeout

Obtiene o establece el número de milisegundos que transcurren antes de que se agote el tiempo de espera si una operación de escritura no finaliza.Gets or sets the number of milliseconds before a time-out occurs when a write operation does not finish.

Métodos

Close() Close() Close() Close()

Cierra la conexión del puerto, establece el valor de la propiedad IsOpen en false y elimina el objeto Stream interno.Closes the port connection, sets the IsOpen property to false, and disposes of the internal Stream object.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
DiscardInBuffer() DiscardInBuffer() DiscardInBuffer() DiscardInBuffer()

Descarta los datos del búfer de recepción del controlador serie.Discards data from the serial driver's receive buffer.

DiscardOutBuffer() DiscardOutBuffer() DiscardOutBuffer() DiscardOutBuffer()

Descarta los datos del búfer de transmisión del controlador serie.Discards data from the serial driver's transmit buffer.

Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos que usa Component.Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa SerialPort y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the SerialPort and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetPortNames() GetPortNames() GetPortNames() GetPortNames()

Obtiene una matriz con los nombres de los puertos serie del equipo actual.Gets an array of serial port names for the current computer.

GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Open() Open() Open() Open()

Abre una nueva conexión de puerto serie.Opens a new serial port connection.

Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

Lee varios bytes del búfer de entrada de SerialPort y los escribe en una matriz de bytes en la posición de desplazamiento especificada.Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified offset.

Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

Lee un número de caracteres del búfer de entrada de SerialPort y los escribe en una matriz de caracteres en la posición de desplazamiento especificada.Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset.

ReadByte() ReadByte() ReadByte() ReadByte()

Lee sincrónicamente un byte del búfer de entrada de SerialPort.Synchronously reads one byte from the SerialPort input buffer.

ReadChar() ReadChar() ReadChar() ReadChar()

Lee sincrónicamente un carácter del búfer de entrada de SerialPort.Synchronously reads one character from the SerialPort input buffer.

ReadExisting() ReadExisting() ReadExisting() ReadExisting()

Lee todos los bytes inmediatamente disponibles, basándose en la codificación, en la secuencia y el búfer de entrada del objeto SerialPort.Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.

ReadLine() ReadLine() ReadLine() ReadLine()

Lee hasta el valor de NewLine en el búfer de entrada.Reads up to the NewLine value in the input buffer.

ReadTo(String) ReadTo(String) ReadTo(String) ReadTo(String)

Lee una cadena hasta el value especificado en el búfer de entrada.Reads a string up to the specified value in the input buffer.

ToString() ToString() ToString() ToString()

Devuelve una String que contiene el nombre del Component, si existe.Returns a String containing the name of the Component, if any. Este método no se debe invalidar.This method should not be overridden.

(Inherited from Component)
Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

Escribe un número especificado de bytes en el puerto serie utilizando los datos de un búfer.Writes a specified number of bytes to the serial port using data from a buffer.

Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32)

Escribe un número especificado de caracteres en el puerto serie utilizando los datos de un búfer.Writes a specified number of characters to the serial port using data from a buffer.

Write(String) Write(String) Write(String) Write(String)

Escribe la cadena especificada en el puerto serie.Writes the specified string to the serial port.

WriteLine(String) WriteLine(String) WriteLine(String) WriteLine(String)

Escribe la cadena especificada y el valor de NewLine en el búfer de salida.Writes the specified string and the NewLine value to the output buffer.

Eventos

DataReceived DataReceived DataReceived DataReceived

Indica que se recibieron datos a través de un puerto representado por el objeto SerialPort.Indicates that data has been received through a port represented by the SerialPort object.

Disposed Disposed Disposed Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
ErrorReceived ErrorReceived ErrorReceived ErrorReceived

Indica que hubo un error en el puerto representado por el objeto SerialPort.Indicates that an error has occurred with a port represented by a SerialPort object.

PinChanged PinChanged PinChanged PinChanged

Indica que hubo un evento de señal que no es de datos en el puerto representado por el objeto SerialPort.Indicates that a non-data signal event has occurred on the port represented by the SerialPort object.

Seguridad

SecurityPermission
Para poder llamar a código no administrado.for the ability to call unmanaged code. Enumeración asociada: UnmanagedCodeAssociated enumeration: UnmanagedCode

Se aplica a