Donald Palmer

Donald Palmer

  • 1.7k
  • 37
  • 1.5k

How to get serialPort_DataReceived into UI ListBox?

Apr 23 2022 12:34 AM

Working on an application that uses TWO Serial Ports. It basically takes data from one port and pass it to the other; and vise verse.

To aid in troubleshooting the system it's doing this for, I wanted to put the Received Data into a ListBox on the Main UI Window. The serialPort_DataReceived method is static and can't cross-thread to the UI Controls. Searching online for a way to do this, I saw I should use Invoke. I've tried to get that to work but have not been able. Any ideas would be greatly appreciated. Code follows ..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace SerialPortTest
{
    public partial class Form1 : Form
    {
        static SerialPort serialPortPIC2;
        public delegate void AddListItemsDelegateType(String text);
        public AddListItemsDelegateType AddListItemsDelegate;
        public Form1()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Load += StartApplication;
        }

        // Start Application
        private void StartApplication(object sender, EventArgs e)
        {
            serialPortPIC2 = new SerialPort("COM6");
            serialPortPIC2.Open();
            serialPortPIC2.BaudRate = 19200;
            serialPortPIC2.ReadTimeout = 500;
            serialPortPIC2.NewLine = System.Char.ToString('\r');
            // Create new Serial COM Port Data Received Event Handler
            serialPortPIC2.DataReceived += new SerialDataReceivedEventHandler(serialPortPIC2_DataReceived);

            // Create new AddListItemsDelegateType
            AddListItemsDelegate += new AddListItemsDelegateType(AddListItemsMethod);

            // Send READY Command to PIC2 - reply is "OK\r"
            serialPortPIC2.WriteLine("ready");
        }

        // Add List Items Method
        public void AddListItemsMethod(String text)
        {
            listBox1.Items.Add(text);   // listBox1 is Designer created ListBox
        }

        // Serial COM Port Data Received Event Handler
        public static void serialPortPIC2_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = sender as SerialPort;

            string indata = sp.ReadLine();
            string outdata = indata.TrimEnd('\r');
            // want to Invoke AddListItemsDelegate but VS doesn't 'see' "AddListItemsMethod" or "AddListItemsDelegate"
            // only "AddListItemsDelegateType"
        }
    }
}