Managing Ports and Transfers in .NET
int comPortIndex;
String dataToWrite = "hello";
String newReceivedData;
// The index of the selected COM port in the name array.
comPortIndex = 3;
UserPort1.SelectedPort.PortName = ComPorts.myPortNames[comPortIndex];
UserPort1.SelectedPort.BaudRate = 115200;
UserPort1.SelectedPort.Open();
newReceivedData = UserPort1.SelectedPort.ReadExisting();
UserPort1.SelectedPort.Write(dataToWrite);
UserPort1.SelectedPort.Close();
!
4
6
The user interface in COM-port applications often provides a way for users to
select a COM port and port parameters using combo boxes. The combo boxes
can reside on the application’s main form, or to minimize clutter, the main form
can have a button the user clicks to open a dialog box that contains the combo
boxes (Figure 10-1). The _Load event for the dialog box that displays the
combo boxes can call a routine that initializes the combo boxes.
To initialize a combo box with the names of the system’s ports, use the Data-
Source property to populate the combo box with the port names retrieved with
GetPortNames:
cmbPort.DataSource = SerialPort.GetPortNames
cmbPort.DataSource = SerialPort.GetPortNames;
An application might need to change the contents of this combo box at times to
reflect the attachment or removal of virtual COM ports. For example, an appli-
cation might update the contents every time a user displays the form that con-
tains the combo box. To update the contents, set the DataSource property
again.