强制应用程序在系统关闭时关闭 [英] Force application close on system shutdown

查看:111
本文介绍了强制应用程序在系统关闭时关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows Forms应用程序,当主窗口关闭时,它会显示一个基本对话框,以确认操作.如果用户决定取消,则退出应用程序将被取消.

I have a Windows Forms application that when the Main Window is closing, it displays a basic dialog box, confirming the action. If the user decides to cancel the application exit is cancelled.

但是,当应用程序最小化运行并且用户想要关闭PC时,由于我的应用程序正在等待用户确认应用程序关闭(显示对话框),因此关闭序列停止.

However, when the application is running minimized and the user wants to shut down the PC, the shutdown sequence stops because my application is waiting on the user to confirm the application close (the dialog box is displayed).

我想到了添加一个计时器来进行超时,如果在一定时间内没有答案,请自动关闭该应用程序,但是即使这是一种方法,也肯定不是每个其他应用程序都可以做到这一点

I thought of adding a timer for making a timeout and if no answer comes in a certain amount of time, close the application automatically, but even if this is a way to do it, it's certainly NOT how every other app does it.

那么在其他所有情况下,除非系统关闭,有什么最佳的解决方案来确认应用程序关闭?

So what would there be an optimal solution to confirm the application shutdown in every other case, unless the system is shutting down?

谢谢!

推荐答案

在FormClosing事件中,检查 CloseReason 属性看看为什么窗户要关闭.如果它是 CloseReason.WindowsShutDown ,则不显示对话框,也不要取消关闭表单.

In your FormClosing event check the FormClosingEventArgs' CloseReason property to see why the window is closing down. If it is CloseReason.WindowsShutDown then don't show your dialog and do not cancel the closing of your form.

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    // Verify that we're not being closed because windows is shutting down.
    if (e.CloseReason != CloseReason.WindowsShutDown)
    {
        // Show your dialog / cancel closing. 
    }
}

注意事项:您可能还希望包含 CloseReason.TaskManagerClosing ,因为用户明确希望在这种情况下关闭您的应用程序,并且任务管理器已要求确认.或者,仅显示 CloseReason.UserClosing 的对话框.

N.B: You might also want to include CloseReason.TaskManagerClosing as the user clearly wants to close your application in that scenario and the taskmanager already asks for confirmation. Or alternatively only show your dialog for CloseReason.UserClosing.

这篇关于强制应用程序在系统关闭时关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆