FormClosing事件未调用MDI子表单

Roo*_*ian 4 c# mdi mdichild winforms

我打算在打开一个新的时候关闭一个公式.关闭公式时,我想在结束事件中处理一些特殊逻辑.但是,在FormClosing和Closing事件中,也不在抽象基类中或在给定的手动附加事件中都不会调用结束事件form_FormClosing.

当我通过单击x手动关闭表单时,所有事件都被解雇了.调用该Close()方法失败.

你有一些建议来解决我的问题吗?

的MdiParent:

private Form _currentForm;
private void ShowForm<T>() where T : Form
{
    if (_currentForm != null && !_currentForm.IsDisposed)
    {
        _currentForm.Hide();
        _currentForm.Close();
    }

    var form = MdiChildren.FirstOrDefault(f => f.GetType() == typeof(T));
    if (form == null)
    {
        form = _formFactory.CreateForm<T>();
        form.MdiParent = this;
        form.WindowState = FormWindowState.Maximized;
        form.FormClosing += form_FormClosing;
        _currentForm = form;
        MdiBackground.Hide();
        form.Show();
    }
    else
    {
        ActivateMdiChild(form);
        form.Activate();
    }
}

void form_FormClosing(object sender, FormClosingEventArgs e)
{
    // will not be called
}
Run Code Online (Sandbox Code Playgroud)

抽象通用mdi子形式:

public abstract partial class BaseForm<TEntity> : Form where TEntity : class, IEntity
{
    protected override void OnClosing(CancelEventArgs e)
    {
        // wil not be called
        if (EditMode == EditModes.Editable)
        {
            MessageBox.Show(this, "Please commit or abort your changes");
            e.Cancel = true;
        }
        base.OnClosing(e);
    }
 }
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

这是行为不端,因为本机Windows MDI实现不支持隐藏MDI子窗口.Winforms使用技巧仍然支持Hide(),它实际上会破坏本机窗口并在再次调用Show()时重新创建它.这有副作用,但是Close()调用不再引发FormClosing/Closed事件,因为Native()调用已经破坏了本机窗口.这是一个bug,在Winforms中并不罕见.

解决方法很简单,当您调用Close()时不需要Hide(),只需将其删除即可.