【问题标题】:Close program before shut-down关机前关闭程序
【发布时间】:2014-07-07 00:21:49
【问题描述】:

我正在为一家公司编写程序,我为供应商编写了程序。 不幸的是,其中一位 IT 经理看到,员工在关闭计算机之前不会关闭此程序,他对我说,您的应用程序必须在关闭之前自行关闭。我告诉他,这不是问题,windows 关闭了这个程序,但他说我不想看到(Windows [windows 等待后台程序关闭])。

在这之后我找到了这段代码:

        static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
    {
        switch (e.Reason)
        {
            case SessionEndReasons.Logoff:
                Application.Exit();
                break;

            case SessionEndReasons.SystemShutdown:
                Application.Exit();
                break;
        }
    }

然后将其添加到 Form_Load 中:

            SystemEvents.SessionEnding += SystemEvents_SessionEnding;

如果你在 Application.Exit() 之前写了一个消息框,它会毫无问题地显示它,但是它不起作用,我可以再次看到(等待后台程序关闭的窗口)。

为什么?!我的代码有什么问题吗?!还有其他方法吗?

谢谢

【问题讨论】:

  • 当您“正常”关闭应用程序时,您的应用程序是否会快速关闭 - 还是需要相当长的时间才能关闭(例如活动后台线程)?
  • @BernhardHiller , 它包含关闭前的后台线程
  • 后台线程是如何“结束”的——直接杀死它们还是等待它们退出?我想问题在于他们在关机时的处理;一个简单的杀戮可能是合适的。
  • @BernhardHiller 是的,我只是杀了他们。我在 SystemEvents_SessionEnding() 方法中使用了终止进程代码,它不起作用,我认为在终止或关闭我的进程之前... Windows 理解后台进程正在运行,如果我终止此进程,Windows 不理解它已关闭。你觉得怎么样 ?!我说的对吗?

标签: c# windows shutdown


【解决方案1】:

正如这篇帖子Is there a way in c# to detect a Windows shutdown/logoff and cancel that action (after asking the user) 所说,似乎它无法暂停超时问题。

也许你可以试试MSDN SessionEnding中的例子:

private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg==WM_QUERYENDSESSION)
    {
        MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
        systemShutdown = true;
    }

    // If this is WM_QUERYENDSESSION, the closing event should be
    // raised in the base WndProc.
    base.WndProc(ref m);

} //WndProc 

private void Form1_Closing(
    System.Object sender, 
    System.ComponentModel.CancelEventArgs e)
{
    if (systemShutdown)
        // Reset the variable because the user might cancel the 
        // shutdown.
    {
        systemShutdown = false;
        if (DialogResult.Yes==MessageBox.Show("My application", 
            "Do you want to save your work before logging off?", 
            MessageBoxButtons.YesNo))
        {
            e.Cancel = true;
        }
        else
        {
            e.Cancel = false;
        }
    }
}

Shutdown Changes for Windows Vista 可能会提供更多关于关机超时的信息

【讨论】:

    【解决方案2】:

    尝试 Environment.Exit(0);而不是 Application.Exit();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      相关资源
      最近更新 更多