Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a form has been closed c#

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 worker started and running. I also want to exit the while(aBackgroundWorker.IsBusy) loop if the button on myForm was clicked.

//MyProgram.cs

using(CustomForm myForm = new CustomForm())
{
    myForm.Show(theFormOwner);
    myForm.Refresh();

    while(aBackgroundWorker.IsBusy)
    {
        Thread.Sleep(1);
        Application.DoEvents();
    }
}

Right now, in the CustomForm the Button_clicked event, I have

//CustomForm.cs

private void theButton_Click(object sender, EventArgs e)
{
  this.Close();
}

Do I need to add more code to the CustomForm class, or the location where I declare and initialize the form in order to be able to detect a closure?

like image 345
jkh Avatar asked Jan 05 '12 22:01

jkh


People also ask

Which event that has happen when you close your form?

The Closing event occurs as the form is being closed. When a form is closed, all resources created within the object are released and the form is disposed. If you cancel this event, the form remains opened.

What is form closed?

In mathematics, especially vector calculus and differential topology, a closed form is a differential form α whose exterior derivative is zero (dα = 0), and an exact form is a differential form, α, that is the exterior derivative of another differential form β.

What is the correct C# statement to be used when you need to hide the currently running Windows form?

To hide a form it is necessary to call the Hide() method of the form to be hidden. Using our example, we will wire up the button on the subForm to close the form. Click on the tab for the second form (the subForm) in your design and double click on the button control to display the Click event procedure.


2 Answers

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
}
like image 122
competent_tech Avatar answered Sep 18 '22 23:09

competent_tech


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.

like image 43
Dracorat Avatar answered Sep 18 '22 23:09

Dracorat