Home > Software design >  Communication between 2 Form in C#
Communication between 2 Form in C#

Time:11-29

I am a newbie in C# and I have questions as below:

I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.

Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.

I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.

How to use FC01, FC03,04... for Form2 when Form 1 connected. Code Form1:

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.Ports;
using Modbus.Device;



namespace ATS
{
    public partial class frCommunication : Form
    {
        SerialPort serialPort = new SerialPort();
        ModbusMaster Master;
        public delegate void truyendulieu(string text);
        public truyendulieu truyendata;
        public delegate void truyendulieu1(string text1);
        public truyendulieu1 truyendata1;
        public delegate void truyendulieu2(string text2);
        public truyendulieu2 truyendata2;

        public frCommunication()
        {
            InitializeComponent();
        }

        private void frCommunication_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            cboxPort.Items.AddRange(ports);
            cboxPort.SelectedIndex = 0;
        
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            btnDisconnect.Enabled = true;
            try
            {
                serialPort.PortName = cboxPort.Text;
                serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
                serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
                serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
                serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
                serialPort.Open();
                Master = ModbusSerialMaster.CreateRtu(serialPort);
                Master.Transport.Retries = 0; // don't have to to retries
                Master.Transport.ReadTimeout = 300;//miliseconds

            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (serialPort.IsOpen)
            {
                lblDisplay.Text = "Connected";
                lblDisplay.ForeColor = System.Drawing.Color.Red;
                cboxBaudRate.Enabled = false;

            }
            else
            {
                lblDisplay.Text = "Disconnected";
                MessageBox.Show("Error!");
            }

        }



        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = true;
            btnDisconnect.Enabled = false;
            try
            {
                serialPort.Close();
                lblDisplay.Text = "Disconnected";
                lblDisplay.ForeColor = System.Drawing.Color.Green;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
                txtV_Grid.Text = Convert.ToString(holding_register[0]);
                txtC_Grid.Text = Convert.ToString(holding_register[1]);
                txtP_Grid.Text = Convert.ToString(holding_register[2]);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
            {
                if (truyendata != null || truyendata1 != null)
                {
                    truyendata(txtV_Grid.Text);
                    truyendata1(txtC_Grid.Text);
                    truyendata2(txtP_Grid.Text);

                }
                this.Hide();
            }
        }

        private void txtV_Grid_TextChanged(object sender, EventArgs e)
        {
            if (truyendata != null)
            {
                truyendata(txtV_Grid.Text);
            }
        }

        private void txtC_Grid_TextChanged(object sender, EventArgs e)
        {
            if (truyendata1 != null)
            {
                truyendata1(txtC_Grid.Text);
            }
        }

        private void txtP_Grid_TextChanged(object sender, EventArgs e)
        {
            if (truyendata2 != null)
            {
                truyendata2(txtP_Grid.Text);
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
        {
          
            if (serialPort.IsOpen)
            {

               
                DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dl == DialogResult.Yes)
                {
                    Master.WriteSingleCoil(1, 0, true);
                }
                else
                {
                    Master.WriteSingleCoil(1, 0, false);

                }

            }
        }

            private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
            {
                if (serialPort.IsOpen)
                {
                DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dl == DialogResult.Yes)
                {
                    Master.WriteSingleCoil(1, 0, false);
                }
                else
                {
                    Master.WriteSingleCoil(1, 0, true);

                }
            }
                
            }
     
        }
    }

Code Form2:
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 SymbolFactoryDotNet;

namespace ATS
{
    public partial class frMain : Form
    {
       
        public frMain()
        {
            InitializeComponent();
        }
       
     

        private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frCommunication frm = new frCommunication();
            frm.ShowDialog();
        }

        private void standardControl1_Load(object sender, EventArgs e)
        {

        }

        private void LoadData(string data)
        {
            txtV.Text = "";
            txtV.Text = data;

        }
        private void LoadData1(string data1)
        {
            txtC.Text = "";
            txtC.Text = data1;

        }
        private void LoadData2(string data2)
        {
            txtP.Text = "";
            txtP.Text = data2;

        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            frCommunication frm = new frCommunication();
            frm.truyendata = new frCommunication.truyendulieu(LoadData);
            frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
            frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
            frm.ShowDialog();

        }

        private void txtV_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if(picOn.Visible == false)
            {
                picOn.Visible = true;
                picOff_Grid.Visible = false;
               // standardControl3.DiscreteValue2 = true;                               
            }
            else
            {
                picOn.Visible = false;
                picOff_Grid.Visible = true;
            }
        }

        private void frMain_Load(object sender, EventArgs e)
        {
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.ToString("HH:mm:ss   dd-MM-yyyy");
        }

        private void btnOn_Grid_Click(object sender, EventArgs e)
        {

            

        }

    }
}

CodePudding user response:

When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?

Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2

using System;

namespace Sandbox
{
    public sealed class Connection
    {
        private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
        public static Connection Instance => _instance.Value;

        private Connection()
        { }

        // Implement your Connection Code here.
    }
}

CodePudding user response:

Could you explain more details? I will past connection code inside class Connection afterthat I can use this function for Form2 or not? Please help me check this! This is my connection code:

  private void frCommunication_Load(object sender, EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();
        cboxPort.Items.AddRange(ports);
        cboxPort.SelectedIndex = 0;
        //Click from frMain
        frMain f2 = new frMain(this);
        f2.Show();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        btnConnect.Enabled = false;
        btnDisconnect.Enabled = true;
        try
        {
            serialPort.PortName = cboxPort.Text;
            serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
            serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
            serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
            serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
            serialPort.Open();
            Master = ModbusSerialMaster.CreateRtu(serialPort);
            Master.Transport.Retries = 0; // don't have to to retries
            Master.Transport.ReadTimeout = 300;//miliseconds

        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
}
  • Related