Wednesday, March 5, 2008

Standby or Hibernate Windows Programmatically

One of the features of Microsoft Windows is the ability to enter standby or hibernation power-saving states that can be resumed at a later time. Usually the system is paused using the Start menu. However, using .NET 2.0, this can be achieved in code.
Application Class

The .NET framework defines the Application class that contains static methods that are used to start and stop applications, obtain information about the current program and process Windows messages. In the .NET framework version 2.0 and later, the Application class includes a method named SetSuspendState, which permits a program to request that the computer is suspended.
SetSuspendState Parameters

The SetSuspendState method requires three parameters. The first parameter determines whether the computer is to be put into a standby or hibernation power state. The parameter accepts a PowerState enumeration value of either Hibernate or Suspend accordingly.

The second operand is a Boolean value that tells the command whether to force a suspend. If set to true, the system is suspended immediately. If set to false, a message is sent to every other running process to request a standby or hibernation. This preferred method allows other programs to react to the message and possibly prevent the action.

The third parameter is another Boolean value. This parameter indicates whether standard wake events will cause Windows to resume automatically. An example of a wake event is a network message from a central system that starts the computer in readiness for a remote backup operation.
Requesting a Suspend State

Using the SetSuspendState method as described above, a standby can be requested using the following line of code. In this case, the standby is not forced and the system will restart in response to wake events.

Application.SetSuspendState(PowerState.Suspend, false, false);

The second example below performs a forced hibernation of the system and disables automatic resuming due to wake events. NB: Ensure that you save all work in all active processes before testing this code.

Application.SetSuspendState(PowerState.Hibernate, true, true);

No comments: