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 a ListBox control.
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 ListBox Control.
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 Code Snippets.
Compiling the Code
This example requires:
A project reference to System.Windows.Forms.dll.
Access to the members of the System.Windows.Forms namespace. Add an
Importsstatement if you are not fully qualifying member names in your code. For more information, see Imports Statement (.NET Namespace and Type).
That your form have a ListBox control named
You do not have to use the ListBox control to display the available serial port names. Instead, you can use a ComboBox or other control. If the application does not need a response from the user, you can use a TextBox 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.