Home > OS >  C# multiple Windows Forms cannot reference
C# multiple Windows Forms cannot reference

Time:03-13

I have 2 Windows form1 (monitor 1 - 1920x1080) and form2 (monitor 2 - 1920x1080), 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();
    }
}

CodePudding user response:

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();
    }

}
  • Related