0

I added this in my code:

namespace uartToCs_version_2._0
{
    public partial class formMain : Form
    {
    ==> public static SerialPort serial = new SerialPort();

But I didn't use the design tab, so how should I go about event handling (with the current setup I can use it in other forms too, will that still be possible)? My design file

Tim Jager
  • 119
  • 9
  • 1
    Possible duplicate of [How to Read and Write from the Serial Port](https://stackoverflow.com/questions/1243070/how-to-read-and-write-from-the-serial-port) – Baddack Dec 19 '18 at 16:52

2 Answers2

1

You can register the events either in any method like Load() or in the constructor. I used the constructor below. You can't register event until all the needed properties are setup. I did not show the setup code.

   public partial class Form1 : Form
    {
        public static SerialPort serial = new SerialPort();
        public Form1()
        {
            InitializeComponent();

            serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
        }


        private void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
        }

    }
jdweng
  • 33,250
  • 2
  • 15
  • 20
1
  public Form1()
    {
        InitializeComponent();
        //add DataReceived event of serial
        Form1.serial.DataReceived += serial_DataReceived;          
    } 
    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        //remove DataReceived event of serial
        Form1.serial.DataReceived -= serial_DataReceived;  
    }
    void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        //process data here 
    }
windfog
  • 209
  • 1
  • 8
  • regard serial is static ,so in FormColosed event , remove serial_DataReceived event for gc – windfog Dec 19 '18 at 11:40
  • why is this needed? – Tim Jager Jan 15 '19 at 17:03
  • 1
    if serial is static , it will be collected by GC when it be set to null or app is exit . when Form1 instance closed , Form1 instance probably not been collected by GC , since Form1.serial is living , and Form1.serial.DataReceived reffer the Form1 instance by exec Form1.serial.DataReceived += serial_DataReceived. – windfog Jan 17 '19 at 09:32