【问题标题】:Form Closing Event visual studio c#表单关闭事件visual studio c#
【发布时间】:2017-05-15 09:46:18
【问题描述】:

直奔问题: 在我的主窗体中,我有一个三个按钮可以打开三个不同的窗体。我将向您展示它是如何构建的。

  • MainForm(这里是三个按钮,上面有三个不同的表单名称)

    • 理论 -> 点击此按钮打开TheoryForm
    • 任务 -> 点击此按钮打开TasksForm
    • 竞争 -> 点击此按钮打开CompeteForm

在我的TasksForm 内部有一个按钮,用于打开TheoryForm。这是我的代码:

public partial class TasksForm : Form
{
     public TasksForm()
     {
          InitializeComponent();
     }

     public void TheoryButton_Click(object sender, EventArgs e)
     {
          Form TheoryForm_Child = new TeoriForm();
          TheoryForm_Child.Show();
     }
     //Add some code here so that when `TasksForm` closes, the `TheoryForm_Child` closes too.
}

我想不通的是,当TasksForm 关闭时,TheoryForm 也应该关闭,现在它没有。

【问题讨论】:

    标签: c# forms events


    【解决方案1】:

    尝试在TheoryButton.Click 事件处理程序之外将变量声明为TheoryForm,然后在TaskForm.FormClosing 事件处理程序中使用它来关闭它。

    public partial class TasksForm : Form
    {
        private Form TheoryForm_Child;
    
        public TasksForm()
        {
            InitializeComponent();
            FormClosing += TaskForm_FormClosing;
        }
    
        public void TheoryButton_Click(object sender, EventArgs e)
        {
            TheoryForm_Child = new TeoriForm();
            TheoryForm_Child.Show();
        }
    
        public void TaskForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(TheoryForm_Child != null)
                TheoryForm_Child.Close();
        }
    }
    

    【讨论】:

      【解决方案2】:

      TasksForm 正在创建 TheoryForm 并不意味着当 TasksForm 关闭时,TheoryForm 也将关闭。相反,您应该像这样通过在 TasksForm 中处理关闭的事件来明确关闭它。

      public partial class TasksForm : Form
      {
          Form _TheoryFor_Child = new TheoryForm();
      
          public TasksForm()
          {
            InitializeComponent();
            Closed += TasksForm_Closed;
          }
      
          private void TasksForm_Closed(object sender, EventArgs e)
          {
            _TheoryFor_Child.Close();
          }
      
          private void TheoryButton_Click(object sender, EventArgs e)
          {      
            _TheoryFor_Child.Show();
          }
      }
      

      【讨论】:

        【解决方案3】:

        您需要以某种方式连接父表单和子表单。 例如,给子表单作为所有者的父表单。

        只需调用

         TheoryForm_Child.Show(this);
        

        【讨论】:

          【解决方案4】:

          有一个非常简单的解决方案。您应该像这样使用其他版本的 Show 方法:

          Form TheoryForm_Child = new TeoriForm();
          TheoryForm_Child.Show(this);
          

          就是这样。那么您的表格将成为理论表格的所有者。所以它会在关闭后自动销毁理论形态。

          更多阅读:https://msdn.microsoft.com/en-us/library/szcefbbd%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

          【讨论】:

            猜你喜欢
            • 2014-06-17
            • 2010-09-06
            • 2015-01-21
            • 1970-01-01
            • 1970-01-01
            • 2016-07-12
            • 2015-03-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多