Computer.Ports.OpenSerialPort( )
The OpenSerialPort method can also accept parameters:
myComPort = _
My.Computer.Ports.OpenSerialPort("COM6", 9600, Parity.None, 8, StopBits.One)
Other .NET languages don??™t support the My object and thus can??™t open a
COM port in this way.
Opening a port tests that the port is available and that the parameters are valid.
After opening a port, the application has exclusive use of the port. No other
application or resource can open the same port until the port is closed. An
application can change port parameters such as bit rate and parity while the
port is open.
Attempting to open a port that is in use raises an UnauthorizedAccessException.
To prevent the exception, application code can read the port??™s IsOpen
property to verify that the port is closed before attempting to open it:
If (Not myComPort.IsOpen) Then
myComPort.Open()
End If
Chapter 9
160
if (!( myComPort.IsOpen ))
{
myComPort.Open();
}
Of course it??™s possible that another resource might open the port after reading
IsOpen but before calling the Open method. In that case, the application can
catch the exception and display a message or take other action as needed:
Try
myComPort.Open()
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
End Try
try
{
myComPort.Open();
}
catch ( UnauthorizedAccessException ex )
{
MessageBox.
Pages:
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197