aydinkahriman
aydinkahriman

Reputation: 98

OnFormClosing method of MDI Parent

Whenever I click the red X button to close the MDI Parent form, first it calls all the OnFormClosing methods of the MDI child forms and then OnFormClosing method of the MDI Parent. However, in my OnFormClosing method of the MDI Parent, I can write e.Cancel = true; somewhere in the code. In that case, it should not call the OnFormClosing methods of the MDI child forms.

1-) Is there a way to ensure that closing MDI Parent doesn't trigger OnFormClosing methods of the MDI child forms?

2-) Is there a method for a MDI child so that this method will be called whenever I close that child form and will not be called when I close its parent form?

Upvotes: 0

Views: 1381

Answers (2)

Moha Dehghan
Moha Dehghan

Reputation: 18443

You can use the lower-level method, WndProc and handle the form's WM_CLOSE event:

protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x10) // WM_CLOSE
    {
        // Process the form closing. Call the base method if required,
        // and return from the function if not.
        // For example:
        var ret = MessageBox.Show("Do you really want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (ret == System.Windows.Forms.DialogResult.No)
            return;
    }
    base.WndProc(ref m);
}

Put this code int MDI parent form. It will happen before FormClosing event on the child forms.

Upvotes: 2

V4Vendetta
V4Vendetta

Reputation: 38210

I guess you cannot control it, as stated here

FormClosing event

If the form is a multiple-document interface (MDI) parent form, the FormClosing events of all MDI child forms are raised before the MDI parent form's FormClosing event is raised. Likewise, the FormClosed events of all MDI child forms are raised before the FormClosed event of the MDI parent form is raised. Canceling the FormClosing event of an MDI child form does not prevent the FormClosing event of the MDI parent form from being raised. However, canceling the event will set to true the Cancel property of the FormClosingEventArgs class that is passed as a parameter to the parent form. To force all MDI parent and child forms to close, set the Cancel property to false in the MDI parent form.

Upvotes: 0

Related Questions