Search code examples
c#mdiformclosing

How to prevent MDI main form closing from MDI Child


I have a MDI main form. On it I host a form, and I want it to show a message box before it closes (asking the user whether to save changes).

So far so good, however I have discovered that closing the MDI main form does not raise a MDI child FormClosing event. I figured I will just call MdiChild.Close() in the MDI main's FormClosing event (which does get raised). This seams to work, however it does causes a problem...

In the messagebox that I show, I offer the user to save changes, not to save changes and cancel closing. Normally this works fine, however I can't seem to find a way to cancel MDI main's FormClosing event. Is there a elegant way of doing this?

EDIT: I solved this by throwing an exception (when user decides to cancel the closing procedure) which is caught in MDI main's FormClosing event. In this way I know when I have to cancel the MDI main's FormClosing event and this seams to work fine ... However I just can't believe that this "hax" is the only way of doing this. Surely there is a better way?


Solution

  • I figure that you cancel the close on the childform when the user votes to cancel the close?

    In that case I'd go with this Main form close

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing)
        {
            foreach (Form frm in this.MdiChildren)
            {
                frm.Close();
            }
        }
        e.Cancel = (this.MdiChildren.Length > 0);
    }