简体   繁体   中英

How to set Parent Form WindowState property from Child Form?

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?

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

Pass form 1 ( this ) to a public property in Form 2 and modify it on form 2

Form2 f = new Form2();
f.f1 = this;
f.Show();
// or: new Form2 { f1 = this }.Show();

Form 2:

public Form1 f1;
[...]
[Event:]
f1.WindowState = FormWindowState.Minimized;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM