The pre-installed Visual Studio C# class for manipulating serial ports in C# is found in the following namespace:
1
2
// The class for manipulating serial ports in C#System.IO.Ports.SerialPort
To get a string list of the current active COM ports on the computer, and then populate a combobox with this list, use the code:
1
2
3
// Populates a combobox with a string list of the active serial port names// e.g. "COM3", "COM8"ComboBoxComPorts.ItemsSource = System.IO.Ports.SerialPort.GetPortNames();
The SerialPort class contains an handy enumeration of commonly available baud rates. The following code shows how to populate a combo box with these values.
1
2
3
4
// An enumeration of common baud rates is used to populate// a combo box.foreach (int i in Enum.GetValues(typeof(SerialPort.BaudRate)))
ComboBoxBaudRate.Items.Add(i);
To set up the SerialPort class for use, you have to set the parameters shown in the code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
SerialPort serialPort;
publicvoid ComPortSetup(
int baudRate,
int numDataBits,
string portName,
StopBits stopBits,
Parity parity,
int readBufferSize) {
this.serialPort = new SerialPort();
// Set up serial commsthis.serialPort.BaudRate = baudRate;
this.serialPort.DataBits = numDataBits;
this.serialPort.PortName = portName;
this.serialPort.StopBits = stopBits;
this.serialPort.Parity = parity;
this.serialPort.ReadBufferSize = readBufferSize; //Default dataIList}
Then you can use code like shown below to open and close the serial port for use.
// Opens the port. If already open, will close first.// If null, returns false.publicbool OpenPort() {
try {
if (this.IsOpen())
this.CloseAndDisposePort();
serialPort.Open();
} catch (Exception e) {
MessageBox.Show(Convert.ToString(e));
returnfalse;
}
returntrue;
}
/// <summary>/// Checks whether serial port is open. /// </summary>/// <returns>Returns true is serial port is open, returns false if serial port is closed or null.</returns>publicbool IsOpen() {
if (serialPort != null)
return serialPort.IsOpen;
elsereturnfalse;
}
/// <summary>/// Closes and disposes of serial port./// </summary>publicvoid CloseAndDisposePort() {
serialPort.Close();
serialPort.Dispose();
}