SerialPort 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示串行端口资源。
public ref class SerialPort : System::ComponentModel::Component
public class SerialPort : System.ComponentModel.Component
type SerialPort = class
inherit Component
Public Class SerialPort
Inherits Component
- 继承
示例
下面的代码示例演示了如何使用 SerialPort 类来允许两个用户从两台由 null 调制解调器电缆连接的单独计算机进行聊天。 在此示例中,系统会在聊天之前提示用户输入端口设置和用户名。 两台计算机都必须执行程序才能实现此示例的完整功能。
#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
注解
使用此类可控制串行端口文件资源。 此类提供同步和事件驱动的 I/O、对固定和中断状态的访问,以及对串行驱动程序属性的访问。 此外,此类的功能可以包装在内部 Stream 对象中,通过 BaseStream 属性进行访问,并传递给包装或使用流的类。
类 SerialPort 支持以下编码: ASCIIEncoding、 UTF8Encoding、 UnicodeEncoding、 UTF32Encoding以及 mscorlib.dll 代码页小于 50000 或代码页为 54936 的任何编码。 可以使用备用编码,但必须使用 ReadByte 或 Write 方法并自行执行编码。
使用 GetPortNames 方法检索当前计算机的有效端口。
SerialPort如果在读取操作期间阻止对象,请不要中止线程。 相反,请关闭基流或释放 SerialPort 对象。
构造函数
SerialPort() |
初始化 SerialPort 类的新实例。 |
SerialPort(IContainer) |
使用指定的 IContainer 对象初始化 SerialPort 类的新实例。 |
SerialPort(String) |
使用指定的端口名初始化 SerialPort 类的新实例。 |
SerialPort(String, Int32) |
使用指定的端口名和波特率初始化 SerialPort 类的新实例。 |
SerialPort(String, Int32, Parity) |
使用指定的端口名、波特率和奇偶校验位初始化 SerialPort 类的新实例。 |
SerialPort(String, Int32, Parity, Int32) |
使用指定的端口名、波特率、奇偶校验位和数据位初始化 SerialPort 类的新实例。 |
SerialPort(String, Int32, Parity, Int32, StopBits) |
使用指定的端口名、波特率、奇偶校验位、数据位和停止位初始化 SerialPort 类的新实例。 |
字段
InfiniteTimeout |
指示不应该发生超时。 |
属性
BaseStream |
获取 Stream 对象的基础 SerialPort 对象。 |
BaudRate |
获取或设置串行波特率。 |
BreakState |
获取或设置中断信号状态。 |
BytesToRead |
获取接收缓冲区中数据的字节数。 |
BytesToWrite |
获取发送缓冲区中数据的字节数。 |
CanRaiseEvents |
获取一个指示组件是否可以引发事件的值。 (继承自 Component) |
CDHolding |
获取端口的载波检测行的状态。 |
Container |
获取包含 IContainer 的 Component。 (继承自 Component) |
CtsHolding |
获取“可以发送”行的状态。 |
DataBits |
获取或设置每个字节的标准数据位长度。 |
DesignMode |
获取一个值,用以指示 Component 当前是否处于设计模式。 (继承自 Component) |
DiscardNull |
获取或设置一个值,该值指示 null 字节在端口和接收缓冲区之间传输时是否被忽略。 |
DsrHolding |
获取数据设置就绪 (DSR) 信号的状态。 |
DtrEnable |
获取或设置一个值,该值在串行通信过程中启用数据终端就绪 (DTR) 信号。 |
Encoding |
获取或设置传输前后文本转换的字节编码。 |
Events |
获取附加到此 Component 的事件处理程序的列表。 (继承自 Component) |
Handshake |
使用 Handshake 中的值获取或设置串行端口数据传输的握手协议。 |
IsOpen |
获取一个值,该值指示 SerialPort 对象的打开或关闭状态。 |
NewLine |
获取或设置用于解释 ReadLine() 和 WriteLine(String) 方法调用结束的值。 |
Parity |
获取或设置奇偶校验检查协议。 |
ParityReplace |
获取或设置一个字节,该字节在发生奇偶校验错误时替换数据流中的无效字节。 |
PortName |
获取或设置通信端口,包括但不限于所有可用的 COM 端口。 |
ReadBufferSize |
获取或设置 SerialPort 输入缓冲区的大小。 |
ReadTimeout |
获取或设置读取操作未完成时发生超时之前的毫秒数。 |
ReceivedBytesThreshold |
获取或设置 DataReceived 事件发生前内部输入缓冲区中的字节数。 |
RtsEnable |
获取或设置一个值,该值指示在串行通信中是否启用请求发送 (RTS) 信号。 |
Site | (继承自 Component) |
StopBits |
获取或设置每个字节的标准停止位数。 |
WriteBufferSize |
获取或设置串行端口输出缓冲区的大小。 |
WriteTimeout |
获取或设置写入操作未完成时发生超时之前的毫秒数。 |
方法
事件
DataReceived |
指示已通过由 SerialPort 对象表示的端口接收了数据。 |
Disposed |
在通过调用 Dispose() 方法释放组件时发生。 (继承自 Component) |
ErrorReceived |
指示由 SerialPort 对象表示的端口上发生了错误。 |
PinChanged |
指示由 SerialPort 对象表示的端口上发生了非数据信号事件。 |