Click here to Skip to main content
15,350,244 members
Articles / Programming Languages / C# 4.0
Posted 26 Apr 2010


151 bookmarked

Basic serial port listening application

Rate me:
Please Sign up or sign in to vote.
4.87/5 (67 votes)
9 May 2010CPOL2 min read
Scans for installed serial ports, queries the supported baud rates, and starts listening to the selected serial port.



This is a basic sample of serial port (COM port) listening in C#. This application is connected to a GPS sending ASCII text for test, but the serial port listening part is all byte-oriented.

CodeProject is missing a simple serial port application. Serial port listening applications usually have this only as a part of a bigger solution, while this application does nothing else than list the available COM-ports, list the available baud rates for the selected COM-port, and starts sending the data. In this solution, a form converts the data to ASCII-text and displays it in a text box.

Using the code

The serial port handling code is placed in a class called SerialPortManager. This class contains methods to start and stop listening for data on the serial port.

Finding the installed serial ports

Rather than just assuming the number of serial ports, or leaving it up to the user to know this beforehand, the code finds the installed serial ports. A string array of serial ports is received through a call made in the constructor of the class SerialPortManager.

public SerialPortManager()
    // Finding installed serial ports on hardware
    _currentSerialSettings.PortNameCollection = 
    _currentSerialSettings.PropertyChanged += 
                       new System.ComponentModel.PropertyChangedEventHandler

    // If serial ports is found, we select the first found
    if (_currentSerialSettings.PortNameCollection.Length > 0)
        _currentSerialSettings.PortName = 

Updating baud rates supported by the selected device

When a serial port is selected by the user, a query for supported baud rates is done. Depending on the hardware, different collections of baud rates may be supported. The field dwSettableBaud from the COMMPROP structure is a join of all supported baud rates.

private void UpdateBaudRateCollection()
    _serialPort = new SerialPort(_currentSerialSettings.PortName);

    // Getting COMMPROP structure, and its property dwSettableBaud.
    object p = _serialPort.BaseStream.GetType().GetField("commProp", 
       BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_serialPort.BaseStream);
    Int32 dwSettableBaud = (Int32)p.GetType().GetField("dwSettableBaud", 
       BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(p);


Serial port settings

The class named SerialSettings contains the currently selected serial port settings, and also includes lists of alternatives for the different setting properties. Everything is data bound to the GUI.

Start listening to a serial port

The serial port is instantiated using the currently selected settings:

// Connects to a serial port defined through the current settings
public void StartListening()
    // Closing serial port if it is open
    if (_serialPort != null && _serialPort.IsOpen)

    // Setting serial port settings
    _serialPort = new SerialPort(

     // Subscribe to event and open serial port for data
     _serialPort.DataReceived += 
         new SerialDataReceivedEventHandler(_serialPort_DataReceived);

The actual serial port reading

The actual serial port reading runs in a threadpool. When data is received on the serial port, an event is raised and _serialPort_DataReceived is called.

void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    int dataLength = _serialPort.BytesToRead;
    byte[] data = new byte[dataLength];
    int nbrDataRead = _serialPort.Read(data, 0, dataLength);
    if (nbrDataRead == 0)
    // Send data to whom ever interested
    if (NewSerialDataRecieved != null)
        NewSerialDataRecieved(this, new SerialDataEventArgs(data));

The received byte array is sent to those listening for the event. The class SerialDataEventArgs houses a byte array.

Stop listening

We stop listening by simply closing the serial port. Note that this might deadlock your UI-thread if you are using Invoke in the event handling in your form.

/// Closes the serial port
public void StopListening()

To work around this possible deadlock, a BeginInvoke is needed. And, that is generally good practice as well.

if (this.InvokeRequired)
    // Using this.Invoke causes deadlock when closing serial port,
    // and BeginInvoke is good practice anyway.
    this.BeginInvoke(new EventHandler<SerialDataEventArgs>(
       _spManager_NewSerialDataRecieved), new object[] { sender, e });


A rather simple sample in how to implement serial port listening has been provided.


  • 27 April 2010 - Code clean-up and getting < > to show in the article.
  • 10 May 2010 - Fixing some misspells in the article.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Amund Gjersøe
Norway Norway
No Biography provided

Comments and Discussions

QuestionWhich Statement to Display the Receiving data in Textbox Pin
Member 154521843-Dec-21 0:24
MemberMember 154521843-Dec-21 0:24 
QuestionProblem WIndows 11 Pin
Tomáš Pokorný1-Nov-21 2:28
MemberTomáš Pokorný1-Nov-21 2:28 
QuestionHow did u put values to text box Pin
elephant12365478913-Sep-21 3:25
Memberelephant12365478913-Sep-21 3:25 
QuestionAdd code to display non-printable character Pin
unolegg11-Jul-21 12:52
Memberunolegg11-Jul-21 12:52 
QuestionBinary Data Parse Pin
Piotr669-Oct-20 11:47
MemberPiotr669-Oct-20 11:47 
AnswerRe: Binary Data Parse Pin
Member 1515205217-Jun-21 6:39
MemberMember 1515205217-Jun-21 6:39 
GeneralMy vote of 5 Pin
Member 1219951431-Aug-20 9:52
MemberMember 1219951431-Aug-20 9:52 
QuestionVote of 5 Pin
Steve Hageman10-Dec-19 17:42
MemberSteve Hageman10-Dec-19 17:42 
GeneralMy vote of 5 Pin
uhoh2111-Oct-19 21:07
Memberuhoh2111-Oct-19 21:07 
QuestionVery Nice, but how to read data from multiple com ports in single window in single time Pin
Member 1192794213-May-19 0:39
MemberMember 1192794213-May-19 0:39 
PraiseUltimate Solution Pin
Santosh Biradar15-Mar-18 1:00
MemberSantosh Biradar15-Mar-18 1:00 
Questionspliting str string Pin
sagram00017-Dec-17 9:53
Membersagram00017-Dec-17 9:53 
QuestionRead data via usb port Pin
Nykhael27-Apr-17 10:54
MemberNykhael27-Apr-17 10:54 
QuestionAm Using RS 232C Port Weight scale is connecting with my laptop comport. I thing it's coming Under Com1 Pin
Member 1315069626-Apr-17 2:57
MemberMember 1315069626-Apr-17 2:57 
PraiseThank you from the future Pin
Member 1259240720-Apr-17 9:46
MemberMember 1259240720-Apr-17 9:46 
QuestionYou saved my life Pin
Member 1238825222-Feb-17 0:13
MemberMember 1238825222-Feb-17 0:13 
Question"dwSettableBaud" and "commProp" ? Pin
YDLU15-Jul-16 6:08
MemberYDLU15-Jul-16 6:08 
PraiseThis just saved me a few hours of work Pin
HoshiKata13-Jul-16 7:23
MemberHoshiKata13-Jul-16 7:23 
PraiseRe: This just saved me a few hours of work Pin
Amund Gjersøe2-Aug-16 7:01
MemberAmund Gjersøe2-Aug-16 7:01 
QuestionApplication returns gibberish Pin
yanwang091423-Jun-16 5:30
Memberyanwang091423-Jun-16 5:30 
AnswerRe: Application returns gibberish Pin
HoshiKata13-Jul-16 7:20
MemberHoshiKata13-Jul-16 7:20 
QuestionCannot receive data from the bluetooth device Pin
Member 123635542-Mar-16 22:00
MemberMember 123635542-Mar-16 22:00 
Questionwrite straight to file Pin
darioits7-May-15 23:23
Memberdarioits7-May-15 23:23 
Questionhow can i send data to serial port using the same program Pin
Sulman Bin Khurshid1-May-15 0:03
MemberSulman Bin Khurshid1-May-15 0:03 
QuestionHOw to make this work for multiple COM Ports? Pin
krishnaramu29-Jan-15 8:05
Memberkrishnaramu29-Jan-15 8:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.