Monday, November 8, 2010

Cancel / Delay Shutting Down of Windows

In the previous post I showed, how to discover whether the computer is shutting down.
This post shows how to cancel / delay the shutting down to save data before, example.
In the previous post the function FormClosing() was used, in which the reason for quitting was determined. With this function we also can easily delay the shutting down by setting e.Cancel = true. Now though the shutting down is not fully cancelled, but just delayed until the program is stopped - now for example the application has time to save unsaved data.
In Windows Vista and higher a dialog pops up saying that a program is delaying the shutdown.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
        e.Cancel = true;
}

Another possibility to delay the shutting down of Windows is to use the Microsoft.Win32.SystemEvents.SessionEnding event, which is called when the system is shutting down. The event can be assigned a function handler like other events (e.g. a click on a button), which is called when the event occurs.
The following code sample shows this:

        private void Form1_Load(object sender, EventArgs e)
        {
            Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(this.WinShutdown);
        }

        private void WinShutdown(object sender, Microsoft.Win32.SessionEndingEventArgs e)
        {
            e.Cancel = true;
        }

No comments:

Post a Comment