Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms not closing properly if terminated due to program exit / main form close

Tags:

c#

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());
}
like image 951
natli Avatar asked Jul 13 '12 13:07

natli


1 Answers

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.

like image 173
Andriy Kizym Avatar answered Oct 15 '22 01:10

Andriy Kizym