Detect when a form has been closed c#

前端 未结 7 1972
猫巷女王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: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();
    }
    

提交回复
热议问题