Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 关机前关闭程序_C#_Windows_Shutdown - Fatal编程技术网

C# 关机前关闭程序

C# 关机前关闭程序,c#,windows,shutdown,C#,Windows,Shutdown,我为一家公司写了一个程序,我为供应商写了一个程序。 不幸的是,一位IT经理看到,员工在关闭计算机之前不会关闭此程序,他对我说,您的应用程序必须在关闭之前自行关闭。我告诉他,这不是问题,windows关闭了这个程序,但他说我不想看到(windows[windows等待后台程序关闭]) 在此之后,我发现以下代码: static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) {

我为一家公司写了一个程序,我为供应商写了一个程序。 不幸的是,一位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()之前编写messagebox,它会毫无问题地显示出来,但它不工作,我可以再次看到(windows正在等待后台程序关闭)

为什么?!我的代码有问题吗?!还有别的办法吗

谢谢

正如这篇文章所说,似乎无法暂停暂停问题

或许您可以尝试以下示例:


可能提供有关关机超时的详细信息。请尝试环境。退出(0);而不是Application.Exit()

应用程序在“正常”关闭时是否会快速关闭?或者关闭(例如,活动后台线程)是否需要相当长的时间?@BernhardHiller,它在关闭前包含后台线程后台线程如何“结束”-只杀死它们还是等待它们退出?我猜问题在于他们在关机时的处理方式;一个简单的杀戮也许是合适的。@BernhardHiller是的,我只是杀了他们。我在SystemEvents_SessionEnding()方法中使用了一个kill进程代码,它不起作用,我认为在终止或关闭进程之前。。。Windows知道后台的进程正在运行,如果我杀死这个进程,Windows不知道它已关闭。你怎么认为?!我说得对吗?
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;
        }
    }
}