Tim Jager
Tim Jager

Reputation: 119

C# serial events when the serial is not in design

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

Upvotes: 0

Views: 81

Answers (2)

windfog
windfog

Reputation: 209

  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 
    }

Upvotes: 1

jdweng
jdweng

Reputation: 34421

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)
        {
        }

    }

Upvotes: 1

Related Questions