c# - 如果由于程序退出/主窗体关闭而终止,则窗体无法正常关闭

标签 c#

在名为“Dev”的表单上,我有以下 OnFormClosing 函数来确保在用户关闭表单时正确关闭线程。

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

如果我直接关闭“Dev”表单,工作正常。但是,如果“Dev”窗体因为主窗体(“Form1”)关闭(导致程序退出)而关闭,则永远不会调用“Dev”中的 OnFormClosing() 函数,因此线程继续运行,需要通过任务管理器终止程序的进程。

我该如何解决这个问题?我意识到我可以将一个 OnFormClosing() 函数添加到“Form1”,然后调用“Dev”中的 OnFormClosing() 函数,但我希望有更多的东西干净。

更新:

从主窗体打开开发窗体:

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

主窗体实际上称为“programname.UI.Main”(我知道正确..)并在“Program.cs”中打开(因此程序的入口点):

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new programname.UI.Main());
}

最佳答案

代替

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

试试这个

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

此方法向子窗体显示所有者,所有转到主窗体的事件都应该转到子窗体。

关于c# - 如果由于程序退出/主窗体关闭而终止,则窗体无法正常关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471168/

相关文章:

c# - 是什么阻止了这个任务长时间运行?

c# - 在 DataTable 中查找值

c# - 带有 MethodInfo 和泛型类型参数的 Expression.Call

c# - 使用语句和 Entity Framework 实体

c# - 使用 FileStream.WriteAsync() 时,再次调用该方法时会发生什么

c# - 剑锋GridEX : Cannot get the newly edited value on CellValueUpdated event

c# - 在 C# 中使用 Microsoft Access 和 OleDb 在数据库中添加数据

c# - Udp 发送和接收套接字行为

c# - 鼠标在 Xna 游戏中选取旋转 Sprite

c# - 在 app.config 中设置值 - 没有对程序文件的写入权限