关闭隐藏主窗体的WinForms应用程序

5

我正在尝试通过Form.Closing事件关闭我的WinForms应用程序,并显示自定义消息(你确定要退出吗?是/否)。为此,我已编辑了C#项目中每个窗体的onFormClosing事件,如下所示:

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

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    // Confirm user wants to close
    switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
    {
    case DialogResult.No:
        e.Cancel = true;
        break;
    default:
        break;
    }        
}

当用户点击“是”时,我希望整个应用程序退出。然而,我有一个主窗体作为登录窗体。当用户登录后,主窗体被隐藏,显示不同的窗体。
因此,当用户点击“是”时,整个应用程序并不会结束,因为有一个隐藏的窗体。我该如何确保整个应用程序关闭?
我已经尝试过Application.Exit(),但这会再次触发确认关闭消息框,因为它调用了OnFormClosing事件。
3个回答

6
您可以明确处理 Application.Exit 作为自己的原因:
protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown
       || e.CloseReason == CloseReason.ApplicationExitCall) 
       return;

通过以下方式,您可以在处理程序中使用 Application.Exit() 来正确关闭。 或者,您也可以直接关闭主(隐藏)窗体。


1

Reeds的解决方案是最好的,如果您想尝试,也可以尝试以下方法:

System.Diagnostics.Process.GetCurrentProcess().Kill();

嗯...你可能不应该杀掉自己的应用程序。 - Florian
在某些情况下你可以这样做,但通常使用 Application.Exit 更好。 - Dominic B.

0
你有登录表单的句柄吗?只需调用 loginForm.Close(),并将确认对话框处理放在真正的主窗体中。由于登录表单是传递给 Application.Run() 的表单,关闭它将关闭应用程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接