简体   繁体   English

如何在C#Winform应用程序中从另一个FORM关闭一个FORM

[英]How to close one FORM from another FORM in C# Winform Application

I'm working on C# winform application, in that I want to close one form from the another form ie I have 2 forms Form1 and Form2 and I want to close Form2 from Form1 for that I have written following code on button click event of Form1, but I'm getting the following exception- 我正在使用C#winform应用程序,因为我想从另一个窗体关闭一个窗体,即我有2个窗体Form1和Form2,并且我想从Form1关闭Form2,因为我在Form1的按钮单击事件上编写了以下代码,但出现以下异常-

"Object reference not set to an instance of an object." “你调用的对象是空的。”

private void button_click(object sender, eventArgs e)
{
     Form2.ActiveForm.Disposed+= new EventHandler(closeForm2) // Getting Exception to ***closeForm2***
}

private void closeForm2(object sender, eventArgs e)
{
      Form2.ActiveForm.Dispose();
}

For future readers! 对于未来的读者!

You can use the following code to close one FORM from another FORM in C# Winform Application. 您可以在C#Winform应用程序中使用以下代码从另一个FORM关闭一个FORM。

FrmToBeClosed obj = (FrmToBeClosed)Application.OpenForms["FrmToBeClosed"];
obj.Close();

Those 2 lines of code are self-explanatory! 这两行代码是不言自明的!

That's it! 而已!

ActiveForm returns "Currently active form from this application" = Form you clicked... How you start your Form2? ActiveForm返回“此应用程序中当前处于活动状态的表单” =您单击的表单...如何启动Form2? I think you should define it like 我认为你应该像这样定义

Form2 DetailsForm = null;
public void prepareForm2() //bind this to action to open new form
{
    if (DetailsForm == null)
    {
        DetailsForm = new Form2(this);
    }
}

Than you can just call close()/Dispose/Hide by calling 比起您可以通过调用close()/ Dispose / Hide

private void closeForm2(object sender, eventArgs e)
{
   DetailsForm.Close();
   // or DetailsForm.Hide();
   // or DetailsForm.Dispose();
}

See MSDN -> Form.ActiveForm Property 参见MSDN-> Form.ActiveForm属性

If your application is a multiple-document interface (MDI) application , use the ActiveMdiChild property to obtain the currently active MDI child form. 如果您的应用程序是多文档界面(MDI)应用程序 ,请使用ActiveMdiChild属性获取当前活动的MDI子窗体。

I think you need a void in your MDI-Form like 我认为您需要在MDI表单中添加一个空格,例如

public void closeChild(Type FormType)
{
  foreach(Form form in this.MdiChildren)
  {
    if(typeof(form) == FormType)
    {
       /* what ever you wanna do */
    }
  }
}

Hope I could help :) 希望我能帮助:)

 CloseProgramForm closepf = new CloseProgramForm();
            closepf.ShowDialog();
            if (closeoption == 1)
                e.Cancel = false;
            else
                e.Cancel = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM