【问题标题】:How to prevent the Parent form closing when closing the child form关闭子窗体时如何防止父窗体关闭
【发布时间】:2018-12-19 12:34:13
【问题描述】:

我在 Winforms 中创建了 2 个表单。我在 Form1 中有按钮,在 form2 中有一些文本。 当单击表单中的按钮时,我通过单击事件显示 form2。当我关闭 form2 时,form1 也会关闭。

但我希望不要关闭 form1。

Form1 代码:

    public Form1()
    {
        InitializeComponent();
        button1.Click += Button1_Click;
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        var form = new Form2();
        form.Show();
    }

表格2:

仅显示名称和城市详细信息等详细信息。

我刚刚创建了简单的示例,因为处于起步阶段。

请分享您的想法和想法。

【问题讨论】:

标签: c# windows winforms windows-forms-designer


【解决方案1】:

Form1 应该记住它创建了哪个 Form2。当 Form2 关闭时,它应该通知 Form1,以便 Form1 可以取消其对 Form2 的引用

private Form2 form2 = null;

void ShowForm2(...)
{
    if (this.form2 != null) return; // form2 already shown

    this.form2 = new Form2();
    // make sure you get notified if form 2 is closed:
    this.form2.FormClosed += onFormClosed;
}

void OnFormClosed(object sender, EventArgs e)
{
     if (object.ReferenceEquals(sender, this.form2)
     {
          // form2 notifies that it has been closed
          // form2 will Dispose itself
          this.form2 = null;
     }
}

Form1 和 Form2 的整齐闭合

注意:如果Form1是Closing,最好问Form2是否允许Closing(如果需要询问运营商?)。如果 Form2 不想关闭,请取消关闭 Form1。

如果允许关闭,请记住您关闭了 Form1 并关闭了 Form2。当 Form2 通知 Form1 关闭时,检查你是否正在关闭,如果是,则重新启动关闭程序,这次不会有 Form2,可以正常继续关闭。

【讨论】:

猜你喜欢
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2019-09-30
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
相关资源
最近更新 更多