MDI Parent的OnFormClosing方法

时间:2013-02-13 08:47:50

标签: c# .net winforms

每当我单击红色X按钮关闭MDI Parent窗体时,首先它调用MDI子窗体的所有OnFormClosing方法,然后调用MDI Parent的OnFormClosing方法。但是,在我的MDI Parent的OnFormClosing方法中,我可以在代码中的某处写e.Cancel = true;。在这种情况下,它不应该调用MDI子窗体的OnFormClosing方法。

1-)有没有办法确保关闭MDI Parent不会触发MDI子窗体的OnFormClosing方法?

2-)是否有一个MDI子项的方法,以便每当我关闭该子表单时都会调用此方法,而当我关闭其父表单时不会调用此方法?

2 个答案:

答案 0 :(得分:2)

您可以使用较低级别的方法WndProc并处理表单的WM_CLOSE事件:

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);
}

将此代码放在MDI父表单中。这将发生在儿童表格上的FormClosing事件之前。

答案 1 :(得分:0)

我想你无法控制它,如此处所述

FormClosing event

  

如果表单是多文档界面(MDI)父表单,则   在MDI之前引发所有MDI子表单的FormClosing事件   父表单的FormClosing事件被引发。同样,FormClosed   在FormClosed事件之前引发所有MDI子表单的事件   引发了MDI父表单。取消FormClosing事件   MDI子窗体不会阻止MDI的FormClosing事件   父母的形式从被提出。但是,取消该事件将设置   to true FormClosingEventArgs类的Cancel属性   作为参数传递给父表单。强制所有MDI父母和   子窗体要关闭,在MDI中将Cancel属性设置为false   父母表格。