如何防止一个窗体在 C# 中多次打开,同时保持与它之前的父窗体的连接?

How do I prevent a Form from opening multiple times in C#, while keeping a connection to the parent Form that came before it?

private void button4_Click(object sender, EventArgs e)
    {
        LogoutQuestion log = new LogoutQuestion(this);
        log.Show();
    }

这是菜单表单中的代码。基本上我想做的是询问用户是否要离开程序,如果是,则关闭 LogoutQuestion 窗体和父菜单窗体。关于如何实现这一点有什么想法吗?

namespace Project
{
public partial class LogoutQuestion : Form
{
    Form FormParent = null;
    public LogoutQuestion(Form parent)
    {
        FormParent = parent;
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
        this.FormParent.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

}

以上就是我说的整个LogoutQuestion Form。任何帮助将不胜感激。 :-)

Make LogoutQuestion a dialog(log.ShowDialog();) This way you can also retrieve the result of the users response, since this will return a DialogResult.

使用 ShowDialog 可以使表单成为模式。这意味着它与显示它的父表单相关联。这就像您尝试在其他 windows 程序中保存文件一样。这也意味着在关闭此表单之前,用户无法进行任何其他操作。这也使您可以选择在表单关闭时使用用户操作的结果。

private void button4_Click(object sender, EventArgs e)
{
    LogoutQuestion log = new LogoutQuestion();
    DialogResult dr = log.ShowDialog();
    if(dr != DialogResult.Cancel)
    {
        this.Close();
    }
}