首页 > 解决方案 > 如何检查是否从另一个表单 C# 调用表单

问题描述

我有Form1并且以这种形式,我有这个代码

Form2 frm = new Form2();
frm.ShowDialog();

所以现在是我的问题:如何知道是否form2
在 Button 事件中那样被调用form2
在按钮事件中form2,我想检查是否ShowDialog()被称为FROM FORM1 (NOT FROM ANOTHER FORM),如果单击按钮,form2则关闭!

标签: c#

解决方案


您可以使用Form.Owner 属性

表格1:

Form2 frm = new Form2();
frm.ShowDialog(this); // owner parameter

表格2:

if (this.Owner != null)
{ 
    // Owner is not null, there is a calling form
    // Do something
    if (this.Owner is Form1)
    {
       Form1 form1 = (Form1)this.Owner; // Form1 called this form!
    }
}

推荐阅读