Detect when a form has been closed c#

前端 未结 7 1955
猫巷女王i
猫巷女王i 2020-12-06 16:51

I have a WinForm that I create that shows a prompt with a button. This is a custom WinForm view, as a message box dialog was not sufficient.

I have a background work

相关标签:
7条回答
  • 2020-12-06 17:29

    You should be able to hook into the FormClosing and FormClosed events.

    http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx

    Closing is before it's closed. Closed is after it's closed.

    0 讨论(0)
  • 2020-12-06 17:37

    Handle the FormClosing event of the form to be notified when the form is closing, so you can perform any cleanup.

    0 讨论(0)
  • 2020-12-06 17:41

    A couple things...

    First, it appears that loop is there in order to prevent execution form proceeding while the dialog is open. If that is the case, change you .Show(parent) to .ShowDialog(parent). That will also take care of the rest of your question.

    0 讨论(0)
  • 2020-12-06 17:42

    You might be going overkill. To show a form like a dialog window and wait for it to exit before returning control back to the calling form, just use:

    mySubForm.ShowDialog();

    This will "block" the main form until the child is closed.

    0 讨论(0)
  • 2020-12-06 17:42

    Make sure your background worker supports cancellation and as others have pointed out use the form closed event handler. This code should point you in the right direction:

    using(CustomForm myForm = new CustomForm())
    {
      myForm.FormClosed += new FormClosedEventHandler(ChildFormClosed);
      myForm.Show(theFormOwner);
      myForm.Refresh();
    
    
      while(aBackgroundWorker.IsBusy)
      {
        Thread.Sleep(1);
        Application.DoEvents();
      }
    }
    
    void ChildFormClosed(object sender, FormClosedEventArgs e)
    {
        aBackgroundWorker.CancelAsync();
    }
    
    0 讨论(0)
  • 2020-12-06 17:49

    To detect when the form is actually closed, you need to hook the FormClosed event:

        this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
    
        void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // Do something
        }
    

    Alternatively:

    using(CustomForm myForm = new CustomForm())
    {
        myForm.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
        ...
    }
    
    void MyForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        // Do something
    }
    
    0 讨论(0)
提交回复
热议问题