|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
How to: Show Available Serial Ports in Visual Basic
This topic describes how to use My.Computer.Ports to show the available serial ports of the computer in Visual Basic.
To allow a user to select which port to use, the names of the serial ports are placed in acontrol.
This example loops over all the strings that the My.Computer.Ports.SerialPortNames property returns. These strings are the names of the available serial ports on the computer.
Typically, a user selects which serial port the application should use from the list of available ports. In this example, the serial port names are stored in a ListBox control. For more information, see.
Sub GetSerialPortNames() ' Show all available COM ports. For Each sp As String In My.Computer.Ports.SerialPortNames ListBox1.Items.Add(sp) Next End Sub
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information, see.
Compiling the Code
This example requires:
A project reference to System.Windows.Forms.dll.
Access to the members of thenamespace. Add an Imports statement if you are not fully qualifying member names in your code. For more information, see .
That your form have a ListBox control named ListBox1.
You do not have to use the ListBox control to display the available serial port names. Instead, you can use aor other control. If the application does not need a response from the user, you can use a control to display the information.
The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent application errors, use exception handling, such as the Try...Catch...Finally statement or the Using statement, when using the port names to open ports.