Export (0) Print
Expand All

Power Management in Windows Forms

Your Windows Forms applications can take advantage of the power management features in the Windows operating system. Your applications can monitor the power status of a computer and take action when a status change occurs. For example, if your application is running on a portable computer, you might want to disable certain features in your application when the computer's battery charge falls under a certain level.

The .NET Framework provides a PowerModeChanged event that occurs whenever there is a change in power status, such as when a user suspends or resumes the operating system, or when the AC power status or battery status changes. The PowerStatus property of the SystemInformation class can be used to query for the current status, as shown in the following code example.

public Form1()
{
    InitializeComponent();
    SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
}

void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
    switch (SystemInformation.PowerStatus.BatteryChargeStatus)
    {
        case System.Windows.Forms.BatteryChargeStatus.Low:
            MessageBox.Show("Battery is running low.", "Low Battery", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            break;
        case System.Windows.Forms.BatteryChargeStatus.Critical:
            MessageBox.Show("Battery is critcally low.", "Critical Battery", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            break;              
        default:
            // Battery is okay. 
            break;
    }
}

Besides the BatteryChargeStatus enumerations, the PowerStatus property also contains enumerations for determining battery capacity (BatteryFullLifetime) and battery charge percentage (BatteryLifePercent, BatteryLifeRemaining).

You can use the SetSuspendState method of the Application to put a computer into hibernation or suspend mode. If the force argument is set to false, the operating system will broadcast an event to all applications requesting permission to suspend. If the disableWakeEvent argument is set to true, the operating system disables all wake events.

The following code example demonstrates how to put a computer into hibernation.

if (SystemInformation.PowerStatus.BatteryChargeStatus == System.Windows.Forms.BatteryChargeStatus.Critical)
{
    Application.SetSuspendState(PowerState.Hibernate, false, false);
}
Show:
© 2014 Microsoft