Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# multiple windows form cannot referecne

I have 2 windows form1(monitor 1-1920×1080) and form2(monitor 2-1920×1080), form 1(monitor 1) has 3 functions need to call function from Form2(monitor 2).

I have to create form2(screen2) 3 times in Form1, but they won’t be same form2 right? Any recommendation to solve this issue?

public partial class Form2 : Form
{
    //Variables
    private Form1 _ParentForm; //Add this here

    //Constructor
    public Form2(Form1 parentForm)
    {
        InitializeComponent();
        _ParentForm = parentForm; //Add this here
    }

    public void Rec_image()
    {
        // Form 2 Image
        PictureBox1.Show();
        PictureBox2.Hide();
    }
    public void Charging()
    {
        // Form 2 Image
        PictureBox6.Hide();
        PictureBox1.Hide();
        PictureBox2.Hide();
        PictureBox3.Hide();
        PictureBox4.Hide();
        PictureBox5.Hide();
        PictureBox7.Show();
    }


}

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(this);
        form2.Show();
    }
    
    private async void Button2_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(this);
        form2.Rec_image();
    }
    
    private void Button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(this);
        form2.Charging();
    }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Store the reference to Form2 instance in a field of Form1 class and you can access the same instance again and again.

public partial class Form1 : Form
{
    private Form2 _form2; // field

    private void Form1_Load(object sender, EventArgs e)
    {
        _form2 = new Form2(this);
        _form2.Show();
    }
    
    private async void Button2_Click(object sender, EventArgs e)
    {
        _form2.Rec_image();
    }
    
    private void Button1_Click(object sender, EventArgs e)
    {
        _form2.Charging();
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading