Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 637
Johnny Avatar asked May 23 '11 00:05

Johnny


1 Answers

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;
}
like image 184
oxilumin Avatar answered Oct 19 '22 17:10

oxilumin