C# – How to set Parent Form WindowState property from Child Form

cwinforms

I have two forms for my C# application. The main form has its ControlBox set to false and then creates the second form like so:

this.ControlBox = false;
new Form2().Show();

The second form is able to minimize and maximize. I need the main form WindowState property to be able to be set from the child form when the window is minimized or returning to its normal state.

The problem I am having is that the program crashes when I try to minimize the child window.

This is my code:

private void Form2_SizeChanged(object sender, EventArgs e)
{
    if(this.WindowState != FormWindowState.Maximized)
        this.Parent.WindowState = this.WindowState;
}

How can I get around this?

Best Answer

Your problem is that Form2 Parent property is null, calling Show() method doesn't actually set the Parent property of the shown Form (check it in debugger). The simplest workaround would be to pass Form1 (calling Form) reference through constructor of the Form2 (called Form) and than use that reference to set the WindowState property. Something like this:

public partial class Form2 : Form
{
    Form1 form1;
    public Form2(Form1 frm)
    {
        InitializeComponent();
        form1 = frm;
        this.SizeChanged +=Form2_SizeChanged;
    }

    private void Form2_SizeChanged(object sender, EventArgs e)
    {
        if (this.WindowState != FormWindowState.Maximized)
            form1.WindowState = this.WindowState;
    }
} 

And than in the code of the Form1 you could change to:

this.ControlBox = false;
Form2 frm = new Form2(this);
frm.Show();
Related Topic