Serial Port Класс
Определение
Представляет ресурс последовательного порта. Represents a serial port resource.
Примеры
В следующем примере кода показано использование SerialPort класса, чтобы два пользователя могли общаться с двух отдельных компьютеров, Соединенных нуль-модемным кабелем. 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. В этом примере пользователям предлагается ввести параметры порта и имя пользователя перед разговором. In this example, the users are prompted for the port settings and a username before chatting. Для обеспечения полной функциональности этого примера оба компьютера должны выполнять программу. Both computers must be executing the program to achieve full functionality of this example.
Комментарии
Используйте этот класс для управления файловым ресурсом последовательного порта. Use this class to control a serial port file resource. Этот класс обеспечивает синхронный и управляемый событиями ввод-вывод, доступ к состояниям ПИН-кода и прерываний, а также доступ к свойствам последовательного драйвера. This class provides synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. Кроме того, функциональные возможности этого класса могут быть заключены во внутренний Stream объект, доступны через BaseStream свойство и переданы в классы, которые переносятся в оболочку или используют потоки. 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.
SerialPortКласс поддерживает следующие кодировки: ASCIIEncoding , UTF8Encoding , UnicodeEncoding , UTF32Encoding и любую кодировку, определенную в mscorlib.dll, где кодовая страница меньше 50000 или кодовая страница 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. Можно использовать альтернативные кодировки, но необходимо использовать ReadByte Write метод или и выполнить кодирование самостоятельно. You can use alternate encodings, but you must use the ReadByte or Write method and perform the encoding yourself.
GetPortNamesМетод используется для получения допустимых портов для текущего компьютера. You use the GetPortNames method to retrieve the valid ports for the current computer.
Если SerialPort объект блокируется во время операции чтения, не прерывайте поток. If a SerialPort object becomes blocked during a read operation, do not abort the thread. Вместо этого закройте базовый поток или удалите SerialPort объект. Instead, either close the base stream or dispose of the SerialPort object.
Конструкторы
Инициализирует новый экземпляр класса SerialPort. Initializes a new instance of the SerialPort class.
Инициализирует новый экземпляр класса SerialPort, используя указанный объект IContainer. Initializes a new instance of the SerialPort class using the specified IContainer object.
Инициализирует новый экземпляр класса SerialPort, используя указанное имя порта. Initializes a new instance of the SerialPort class using the specified port name.
Инициализирует новый экземпляр класса SerialPort, используя указанное имя порта и скорость передачи в бодах. Initializes a new instance of the SerialPort class using the specified port name and baud rate.
Инициализирует новый экземпляр класса SerialPort, используя указанное имя порта, скорость передачи в бодах и бит четности. Initializes a new instance of the SerialPort class using the specified port name, baud rate, and parity bit.
Инициализирует новый экземпляр класса SerialPort, используя указанное имя порта, скорость передачи в бодах, бит четности и биты данных. Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, and data bits.
Инициализирует новый экземпляр класса SerialPort, используя указанное имя порта, скорость передачи в бодах, бит четности, биты данных и стоп-бит. Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, data bits, and stop bit.
Указывает, что отсчет времени ожидания не производится. Indicates that no time-out should occur.
Свойства
Возвращает базовый объект Stream для объекта SerialPort. Gets the underlying Stream object for a SerialPort object.
Возвращает или задает скорость передачи для последовательного порта (в бодах). Gets or sets the serial baud rate.
Получает или задает состояние сигнала разрыва. Gets or sets the break signal state.
Возвращает число байтов данных, находящихся в буфере приема. Gets the number of bytes of data in the receive buffer.
Получает число байтов данных, находящихся в буфере отправки. Gets the number of bytes of data in the send buffer.
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Получает состояние линии обнаружения несущей для порта. Gets the state of the Carrier Detect line for the port.
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает состояние линии готовности к приему. Gets the state of the Clear-to-Send line.
Возвращает или задает стандартное число битов данных в байте. Gets or sets the standard length of data bits per byte.
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает или задает значение, показывающее, игнорируются ли пустые байты (NULL), передаваемые между портом и буфером приема. Gets or sets a value indicating whether null bytes are ignored when transmitted between the port and the receive buffer.
Получает или задает состояние сигнала готовности данных (DSR). Gets the state of the Data Set Ready (DSR) signal.
Получает или задает значение, включающее поддержку сигнала готовности терминала (DTR) в сеансе последовательной связи. Gets or sets a value that enables the Data Terminal Ready (DTR) signal during serial communication.
Получает или задает кодировку байтов для преобразования текста до и после передачи. Gets or sets the byte encoding for pre- and post-transmission conversion of text.
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Возвращает или задает протокол установления связи для передачи данных через последовательный порт с использованием значения Handshake. Gets or sets the handshaking protocol for serial port transmission of data using a value from Handshake.
Возвращает значение, указывающее открытое или закрытое состояние объекта SerialPort. Gets a value indicating the open or closed status of the SerialPort object.
Возвращает или задает значение, используемое для интерпретации окончания вызова методов ReadLine() и WriteLine(String). Gets or sets the value used to interpret the end of a call to the ReadLine() and WriteLine(String) methods.
Возвращает или задает протокол контроля четности. Gets or sets the parity-checking protocol.
Возвращает или задает байт, которым заменяются недопустимые байты потока данных при обнаружении ошибок четности. Gets or sets the byte that replaces invalid bytes in a data stream when a parity error occurs.
Получает или задает последовательный порт, в частности, любой из доступных портов COM. Gets or sets the port for communications, including but not limited to all available COM ports.
Возвращает или задает размер входного буфера SerialPort. Gets or sets the size of the SerialPort input buffer.
Получает или задает срок ожидания в миллисекундах для завершения операции чтения. Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.
Возвращает или задает число байтов во внутреннем входном буфере до возникновения события DataReceived. Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs.
Возвращает или задает значение, показывающее, включен ли сигнал запроса передачи (RTS) в сеансе последовательной связи. Gets or sets a value indicating whether the Request to Send (RTS) signal is enabled during serial communication.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Получает или задает стандартное число стоповых битов в байте. Gets or sets the standard number of stopbits per byte.
Возвращает или задает размер выходного буфера последовательного порта. Gets or sets the size of the serial port output buffer.
Получает или задает срок ожидания в миллисекундах для завершения операции записи. Gets or sets the number of milliseconds before a time-out occurs when a write operation does not finish.
Методы
Закрывает соединение порта, присваивает свойству IsOpen значение false и уничтожает внутренний объект Stream. Closes the port connection, sets the IsOpen property to false , and disposes of the internal Stream object.
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Удаляет данные из буфера приема последовательного драйвера. Discards data from the serial driver’s receive buffer.
Удаляет данные из буфера передачи последовательного драйвера. Discards data from the serial driver’s transmit buffer.
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает неуправляемые ресурсы, используемые объектом SerialPort, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the SerialPort and optionally releases the managed resources.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Получает массив имен последовательных портов для текущего компьютера. Gets an array of serial port names for the current computer.
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Открывает новое соединение последовательного порта. Opens a new serial port connection.
Считывает из входного буфера SerialPort определенное число байтов и записывает их в байтовый массив, начиная с указанной позиции. Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified offset.
Считывает из входного буфера SerialPort определенное число символов и записывает их в символьный массив, начиная с указанной позиции. Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset.
Считывает из входного буфера SerialPort один байт в синхронном режиме. Synchronously reads one byte from the SerialPort input buffer.
Считывает из входного буфера SerialPort один символ в синхронном режиме. Synchronously reads one character from the SerialPort input buffer.
Считывает все непосредственно доступные байты в соответствии с кодировкой из потока и из входного буфера объекта SerialPort. Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.
Считывает данные из входного буфера до значения NewLine. Reads up to the NewLine value in the input buffer.
Считывает из входного буфера строку до указанного значения value . Reads a string up to the specified value in the input buffer.
Возвращает объект String, содержащий имя Component, если оно есть. Returns a String containing the name of the Component, if any. Этот метод не следует переопределять. This method should not be overridden.
(Унаследовано от Component)
Записывает указанное число байтов в последовательный порт, используя данные из буфера. Writes a specified number of bytes to the serial port using data from a buffer.
Записывает указанное число символов в последовательный порт, используя данные из буфера. Writes a specified number of characters to the serial port using data from a buffer.
Записывает указанную строку в последовательный порт. Writes the specified string to the serial port.
Записывает указанную строку и значение NewLine в выходной буфер. Writes the specified string and the NewLine value to the output buffer.
События
Указывает, что данные были получены через порт, представленный объектом SerialPort. Indicates that data has been received through a port represented by the SerialPort object.
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Указывает, что произошла ошибка с портом, представленным объектом SerialPort. Indicates that an error has occurred with a port represented by a SerialPort object.
Указывает, что для порта, представленного объектом SerialPort, возникло событие сигнала, не связанного с данными. Indicates that a non-data signal event has occurred on the port represented by the SerialPort object.