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;

namespace ch15_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public delegate void myDelegate();
        public void updateRichTextBox()
        {
            richTextBox1.AppendText(serialPort1.ReadExisting());
            richTextBox1.ScrollToCaret();
        }
        private void DataReceived1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            richTextBox1.BeginInvoke(new myDelegate(updateRichTextBox));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceived1);
            string[]  portNames = System.IO.Ports.SerialPort.GetPortNames();
            foreach (string port in portNames)
                comboBox1.Items.Add(port);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //close serial port if it is open
            if (serialPort1.IsOpen)
                serialPort1.Close();
            try
            {
                //configure the various parameters of serial port
                serialPort1.PortName = comboBox1.Text;
                serialPort1.BaudRate = 9600;
                serialPort1.Parity = System.IO.Ports.Parity.None;
                serialPort1.DataBits = 8;
                serialPort1.StopBits = System.IO.Ports.StopBits.One;
                //   open serial port
                serialPort1.Open();
                //update the status of serial port
                richTextBox1.Text = comboBox1.Text + " is connected\n ";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();
                richTextBox1.Text = serialPort1.PortName + " disconnected ";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //write a string to serial port
                serialPort1.Write(textBox1.Text + "\n");
                //append sent string to richTextBox control
                richTextBox1.AppendText(textBox1.Text + "\n");
                richTextBox1.ScrollToCaret();
                textBox1.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
