简体   繁体   English

如果由于程序退出/主表单关闭而终止,则表单未正确关闭

[英]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. 在名为“Dev”的表单上,我有以下OnFormClosing函数,以确保在用户关闭表单时正确关闭线程。

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. 但是如果“Dev”形式因为主窗体(“Form1”)被关闭(导致程序退出)而OnFormClosing() ,则“Dev”中的OnFormClosing()函数永远不会被调用,因此线程继续运行并且程序'需要通过任务管理器杀死进程。

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. 我意识到我可以在“Form1”中添加一个OnFormClosing()函数,然后在“Dev”中调用OnFormClosing()函数,但我希望能有一些更干净的东西。

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): 主窗体真的叫做“programname.UI.Main”(我知道对..),它在“Program.cs”中打开(所以程序的入口点):

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. 此方法显示子表单的所有者,并且转到主表单的所有事件都应转到子表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM