Johnny
Johnny

Reputation: 383

Parent form closing when child form closes

In my C# application, I have the following method that is called when the main form closes.

private void FormMain_Closing(object sender, FormClosingEventArgs e)
{ 
        // Show this dialog when the user tries to close the main form
        Form testForm = new FormTest();
        testForm.StartPosition = FormStartPosition.CenterParent;
        testForm.ShowDialog();
}   

This creates a dialog window that will show when the main form is closing. However, my issue is that when the user closes testForm, the main form closes immediately after. I've tried all sorts of variants of e.Cancel = true; and such, and still cannot cancel the main form closing.

Any ideas?


Edit: it looks like I'm running into an issue using two ShowModal()'s in succession. Looking into the issue...


Edit: Used this.DialogResult = DialogResult.None; and it seems to have fixed my problem. It is apparently a known issue in WinForms when opening a modal dialog from a modal dialog.

Upvotes: 6

Views: 5249

Answers (3)

Manfred
Manfred

Reputation: 5656

I know that you mention in your question that you have tried to use 'e.Cancel = true;' However, the following code works in my environment (.NET 4.0, Visual Studio 2010, Windows 7):

 private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
     // Show this dialog when the user tries to close the main form
     Form testForm = new FormTest();
     testForm.StartPosition = FormStartPosition.CenterParent;
     testForm.ShowDialog();
     e.Cancel = true;
 }

If this doesn't work in your case you may have other event handlers at work. In that case try this code in a newly generated Windows Forms Application.

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65466

This could to be handled by the children too from the docs:

If a form has any child or owned forms, a FormClosing event is also raised for each one. If any one of the forms cancels the event, none of the forms are closed. Therefore the corresponding FormClosed events are not sent to any of the forms.

Upvotes: 1

oxilumin
oxilumin

Reputation: 4833

This code works fine with me. I think there is a problem in another part of your code.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Form testForm = new FormTest();
    testForm.StartPosition = FormStartPosition.CenterParent;
    testForm.ShowDialog();

    e.Cancel = testForm.DialogResult == DialogResult.Cancel;
}

Upvotes: 2

Related Questions