Disable automatic termination of applications on shutdown

You can do this with some code by handing the SystemEvents.SessionEnding event. This will show a dialog box when you try to logoff or shutdown and ask if you want to cancel the logoff or shutdown.

The code can be compiled for free with either the Visual C# 2008 Express Edition or with the windows SDK.

With the sdk, use the following command:

csc.exe   /out:StopShutdown.exe /target:winexe StopShutdown.cs 

Here's the code:

using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace StopShutdown
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
           string desktopRegKey = @"HKEY_CURRENT_USER\Control Panel\Desktop";
           Registry.SetValue(desktopRegKey, "AutoEndTasks", 0);
           Registry.SetValue(desktopRegKey, "WaitToKillAppTimeout", 20000);
           Registry.SetValue(desktopRegKey, "HungAppTimeout", 20000);

            Form AppForm = new Form()
                {
                    ClientSize = new System.Drawing.Size(0, 0),
                    ControlBox = false,
                    FormBorderStyle = FormBorderStyle.None,
                    Opacity = 0,
                    ShowIcon = false,
                    ShowInTaskbar = false,
                    SizeGripStyle = SizeGripStyle.Hide,
                };

            SystemEvents.SessionEnding += (_e, e) =>
            {
                DialogResult dr = MessageBox.Show(
                                    "Cancel shutdown?"
                                    , "Shutdown",
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1);

                e.Cancel = (dr == DialogResult.Yes);
            };


            Application.Run(AppForm);
        }

    }
}

Edit:

Downloadable source and exe.


If you're willing to do a little registry editing... Start -> Run -> regedit

HKEY_CURRENT_USER\Control Panel\Desktop

Make sure AutoEndTasks is 0, and set WaitToKillAppTimeout to 20000 (the default value of 2 seconds). You can set the value higher if you wish. There's also HungAppTimeout (the defalt is 5000), but that applies more for applications which are not responding.