NET Framework can use the SerialPort class
to access COM-port devices. Applications can use the class??™s properties, methods,
and events to access ports without having to resort to low-level programming
or the Windows API. The SerialPort class was added in version 2.0 of
.NET.
This chapter shows how to use the class to exchange text and binary data. The
code in this chapter uses resources in the following namespaces:
Imports System
Imports System.IO.Ports
using System.IO;
using System.IO.Ports;
Chapter 9
156
.
To access a COM port, an application creates a SerialPort object, sets the communication
parameters, and opens a connection to the port.
The SerialPort class??™s GetPortNames method returns an array of the names of all
of the system??™s COM ports. The array??™s elements aren??™t guaranteed to be in
alphabetical order, but the Array.Sort method can sort if needed.
Dim nameArray() As String
nameArray = SerialPort.GetPortNames
Array.Sort(nameArray)
string[] nameArray = null;
nameArray = SerialPort.GetPortNames();
Array.Sort( nameArray );
Because users can attach and remove virtual COM ports while an application is
running, an application may need to look for ports more than once. Also be
aware that the array index isn??™t the same thing as a port??™s COM-port number.
For example, if a PC??™s only port is COM4, the port??™s SerialPort object will be at
index zero in the array.
Pages:
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194