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

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());
}

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.

链接地址: http://www.djcxy.com/p/61550.html

上一篇: 如何在Eclipse中监控开发人员的工作数据?

下一篇: 如果由于程序退出/主窗体关闭而终止,表单不能正确关闭