SoFunction
Updated on 2025-04-14

Implementation of C# serial port scanner reading data

First, create a tool class CommBar for scanning guns

/// <summary>
    /// Scanning gun (serial port) working class    /// </summary>
    public class CommBar : IDisposable
    {
        /// <summary>
        /// Serial port reference        /// </summary>
        public SerialPort serialPort;

        /// <summary>
        ///Storing converted data values        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// Scanning gun (serial port) working class        /// </summary>
        public CommBar()
        {
            serialPort = new SerialPort();
        }

        /// <summary>
        /// Serial port status        /// </summary>
        public bool IsOpen
        {
            get
            {
                return ;
            }
        }

        /// <summary>
        /// Open the serial port        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            if ()
            {
                Close();
            }
            ();
            if ()
            {
                return true;
            }
            else
            {
                ("Serial port failed to open!");
                return false;
            }
        }

        /// <summary>
        /// Close the serial port        /// </summary>
        public void Close()
        {
            ();
        }

        /// <summary>
        /// Write data        /// </summary>
        /// <param name="send">Data</param>        /// <param name="offSet">offset</param>        /// <param name="count">Bytes</param>        public void WritePort(byte[] send, int offSet, int count)
        {
            if (IsOpen)
            {
                (send, offSet, count);
            }
        }

        /// &lt;summary&gt;
        /// Get the available serial port        /// &lt;/summary&gt;
        /// <returns>Serial port name list</returns>        public string[] GetComName()
        {
            string[] names = null;
            try
            {
                names = (); // Get the names of all available serial ports            }
            catch (Exception)
            {
                ("Serial port not found");
            }
            return names;
        }

        /// &lt;summary&gt;
        /// Register a serial port        /// &lt;/summary&gt;
        /// <param name="portName">Port number</param>        /// <param name="baudRate">BadRate</param>        public void SerialPortValue(string portName, int baudRate)
        {
            //Serial port name             = portName;
            //Bad Rate             = baudRate;
            //Data bit             = 8;
            //Two stops             = ;
            //No parity bits             = ;
             = 100;
            // = -1;
        }

        #region Implement IDisposable
        private bool m_disposed = false;//Identify whether the resource has been released
        /// &lt;summary&gt;
        /// Release        /// &lt;/summary&gt;
        public void Dispose()
        {
            Dispose(true);
            (this);//Prevent Finalize calls        }

        /// &lt;summary&gt;
        /// Release        /// &lt;/summary&gt;
        /// &lt;param name="disposing"&gt;&lt;/param&gt;
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    //Release managed resources                    ();
                }
                //Release unmanaged resources                m_disposed = true;
            }
        }

        /// &lt;summary&gt;
        /// Destructor        /// &lt;/summary&gt;
        ~CommBar()
        {
            Dispose(false);
        }

        #endregion
    }

When using it in a form, you need to instantiate the class. It is recommended to declare the class object outside the constructor first and instantiate the object inside the constructor

CommBar commBar;
        public Form2()
        {
          InitializeComponent();
            commBar = new CommBar();
            //Register a serial port            ("COM1", 9600);
            //Open the serial port            if (())
                //Affiliated event handler                 += new (serialPort_DataReceived);
        }

Next create delegates and events

//Delegate, point to the CodeText method        private delegate void ModifyButton_dg(CommBar commBar);

        //Serial port receiving event handler        // Whenever the serial port talks about data, it is triggered        void serialPort_DataReceived(object sender,  e)
        {
            (100);
            byte[] m_recvBytes = new byte[];//Define the buffer size            int result = (m_recvBytes, 0, m_recvBytes.Length);//Read data from the serial port            if (result &lt;= 0)
                return;
             = (m_recvBytes, 0, m_recvBytes.Length);//Convert the data            (new ModifyButton_dg(CodeText), commBar);//Call the delegate and pass the value to the text box            ();
        }

Assign values ​​to containers such as text boxes

// Used to assign values ​​to text boxes        private void CodeText(CommBar commBar)
        {
          //Add logical judgment, etc.            this.txt_ASN.Text = ;
               
        }

The form needs to display a text description of success or failure, so it is recommended to use it in this way

this.lbl_error.Text = "ASN code already exists!";
  this.lbl_error.Visible = true;
  (3000).ContinueWith(_ =&gt;
   {
      Invoke(new MethodInvoker(() =&gt; {
      lbl_error.Visible = false;

       }));
   });

This is the end of this article about the implementation of C# serial port scanner reading data. For more related contents of C# serial port scanner reading, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!