7

On the form called "Dev" I have the following OnFormClosing function to make sure a thread is closed properly when a user closes the form.

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);
    dev.stopMultipleColorsWatcher();
}

Works fine if I close the "Dev" form directly. But if the "Dev" form closes because the main form ("Form1") was closed (which causes the program to exit) the OnFormClosing() function in "Dev" is never called, so the thread keeps on running and the program' process needs to be killed via task manager.

How do I fix this? I realise I could add an OnFormClosing() function to "Form1" which then calls the OnFormClosing() function in "Dev", but I was hoping for something a bit more clean.

Update:

Dev form is opened from the main form:

private void btn_opendev_Click(object sender, EventArgs e)
{
    Dev frm = new Dev();
    frm.Show();
}

The main form is really called "programname.UI.Main" (I know right..) and it is opened in "Program.cs" (so the program's entry point):

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new programname.UI.Main());
}
natli
  • 3,782
  • 11
  • 51
  • 82

1 Answers1

4

Instead of

    Dev frm = new Dev();
    frm.Show();

try this

    Dev frm = new Dev();
    frm.Show(this);

This method shows an owner to a child form, and all events that go to the main form should go to the child forms.

Andriy Kizym
  • 1,756
  • 2
  • 14
  • 29
  • @HansPassant The form does not run on a seperate thread... I just wanted **a** thread to be closed when the form is closed. Imagine you have a form with two buttons; one to start a thread doing something in an endless loop, and one that ends it. When a user closes the form/the program, would you not want that thread to close? – natli Jul 14 '12 at 09:30