Saturday, November 6, 2010

Discover If System Is Shutting Down

Some people want to get to know via C#, whether the system is currently being shutdown.
Logically, when doing that, all running programs have to be terminated. We will use that and ask for the reason of quitting in the function FormClosing() of the main form, which is called when the form is closed.
The reason can be determined via CloserReason of the argument e. If a shutdown is the reason, this is CloseReason.WindowsShutDown.
The following code snippet displays a message, when the computer is shutting down:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    if (e.CloseReason == CloseReason.WindowsShutDown)
        MessageBox.Show("PC wird heruntergefahren.");

The use of the event Microsoft.Win32.SystemEvents.SessionEnding, which only occurs when the PC is shut down, is explained in the next post.

No comments:

Post a Comment