Reputation: 139
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?
Upvotes: 3
Views: 10078
Reputation: 8656
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();
Upvotes: 6
Reputation: 31
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;
Upvotes: 3