系统关闭时强制关闭应用程序

32

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

但是,当应用程序最小化运行时,如果用户想要关闭PC,则关闭序列会停止,因为我的应用程序正在等待用户确认应用程序关闭(对话框被显示)。

我考虑添加一个计时器来设置超时时间,如果在一定时间内没有回应,就自动关闭应用程序,但即使这是一种方法,它肯定不是每个应用程序都这样做的。

那么,在除系统关机之外的所有其他情况下,如何确认应用程序关闭的最佳解决方案是什么?

谢谢!

5个回答

54
在你的FormClosing事件中,检查FormClosingEventArgsCloseReason属性以查看窗口关闭的原因。如果它是CloseReason.WindowsShutDown,那么不要显示对话框并且不要取消关闭窗体的操作。
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. 
    }
}

N.B: 您可能还想在其中包括 CloseReason.TaskManagerClosing,因为用户在这种情况下明显想关闭您的应用程序,而任务管理器已经要求确认。或者只显示与CloseReason.UserClosing相关的对话框。


10

在Closing事件处理程序中,您可以像这样定义:

    this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);

我猜您是在发布确认对话框的地方,您可以检查theCloseReason参数,如果是关闭导致的,则不要发布对话框:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.WindowsShutDown)
        {
            //do not show the dialog
        }
    }

6

SystemEvents可以帮助您。SessionEnding事件发生在用户尝试注销或关闭系统时。

Microsoft.Win32.SystemEvents.SessionEnding += (sender, e) => DoYourJob();

同上,对我的情况很有用 - 为缺乏验证的应用程序提供“替代”用户界面,并且如果您关闭它,则无法重新启动该应用程序,因为PC被锁定。 - Roger Willcocks

1

0

您可以监听关闭事件并在不弹出消息框的情况下退出应用程序。


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