且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

隐藏MDI子窗体上关闭C#

更新时间:2023-12-06 09:31:52

表单是的打开和关闭由用户。而且,事实上,当它们闭合时,对象实例是受被破坏,从而导致您丢失存储在与该对象实例相关联的字段或属性的所有数据。

Forms are intended to be opened and closed by the user. And, indeed, when they are closed, the object instance is subject to being destroyed, causing you to lose all data that is stored in fields or properties associated with that object instance.

所以,你不应该使用的表单实例作为一个永久的地方来存储数据。你需要写数据到磁盘,将其保存到数据库中,或者简单地将其存储在一个类的实例跨越的所有的你的形式(即,当然也不会被破坏,直到你共享明确地这样做通过code,因为它没有用户界面和用户不能为关闭)。

Therefore, you should not use form instances as a permanent place to store data. You need to write that data out to disk, save it into a database, or perhaps simply store it in a class instance shared across all of your forms (that, of course, will not be destroyed until you explicitly do so through code, as it has no user interface and can't be "closed" by the user).

不过,如果你只想做这项工作,这是可以做到这一点。您需要更改code在的FormClosing 事件处理程序的只有的prevent在关闭子窗体时, e.CloseReason 属性表示,他们正在关闭作为直接用户交互的结果:

However, if you just want to make this work, it's possible to do that as well. You need to change the code in your FormClosing event handler to only prevent the child forms from closing when the e.CloseReason property indicates that they're closing as a result of direct user interaction:

private void ParameterForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        this.Hide();
        e.Cancel = true;
    }
}

这是你的检查不工作的原因( e.CloseReason!= CloseReason.FormOwnerClosing )是因为你有一个MDI应用程序。还有就是当MDI父正在关闭使用一个特殊的原因: CloseReason.MdiFormClosing 。你可以看为的的,但它是简单的做到这一点上面显示的方式,因为你不想prevent从什么时候关闭Windows正在关闭的窗户或者,例如

The reason that your check doesn't work (e.CloseReason != CloseReason.FormOwnerClosing) is because you have an MDI application. There's a special reason that is used when the MDI parent is closing: CloseReason.MdiFormClosing. You could watch for that also, but it's simpler to do it the way shown above, because you don't want to prevent the windows from being closed when Windows is shutting down either, for example.