Search code examples
c#winformsdrawingmultiple-forms

Drawing from one Form on another while the one is closing/closed


I am programming something in c# for school. I have 2 Forms and while I close the child form I want to draw something on the parent Form and I don't want to use any button I would have to click afterwards. This is what I have tried but it doesn't work.

private void button1_Click(object sender, EventArgs e)
    {    
      this.Close(); //Closes Form2(Child)
    }
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        Form1 f1 = new Form1();
        Graphics g;
        g = f1.CreateGraphics();
        g.DrawRectangle(Pens.Black, 100, 100, 50, 50);
    }

I also have tried using the FormClosed event.


Solution

  • On your parent form, when you initialize the child form, set it's Owner property to this:

    var form2 = new Form2();
    form2.Owner = this;
    

    And then from the child form, you can access the parent by doing this:

    Graphics g;
    g = ((Form1)this.Owner).CreateGraphics();
    g.DrawRectangle(Pens.Black, 100, 100, 50, 50);