Reputation: 3063
I have following code:
FORM1
public partial class Form1 : Form
{
Dialog dlg;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dlg = new Dialog();
dlg.Show(this);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (dlg != null && !dlg.IsDisposed)
{
this.RemoveOwnedForm(dlg);
dlg.Dispose();
}
}
}
DIALOG
public partial class Dialog : Form
{
public Dialog()
{
InitializeComponent();
}
private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
}
I need to click twice on "X" button of form1 in order to close it. What can be a problem?
Upvotes: 1
Views: 1203
Reputation: 3063
Solution for this:
private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.FormOwnerClosing)
{
e.Cancel = true;
Hide();
}
}
This solution does not require dlg.Dispose() and this.RemoveOwnedForm(dlg) in Form1_FormClosing event.
Upvotes: 1
Reputation: 216263
I can't try it right now, but in the Dialog_FormClosing you could add this test
if(this.Owner != null)
{
e.Cancel = true;
Hide();
}
From MSDN docs on RemoveOwnedForm:
The form assigned to the owner form remains owned until the RemoveOwnedForm method is called. In addition to removing the owned form from the list of owned form, this method also sets the owner form to null.
Upvotes: 1