Windows 窗体中的电源管理

您的 Windows 窗体应用程序可以利用操作系统中的电源管理功能。 应用程序可以监视计算机的电源状态,并在发生状态更改时采取措施。 例如,如果应用程序在便携式计算机上运行,则可能希望在计算机的电池电量低于特定级别时禁用应用程序中的某些功能。

.NET Framework 提供了一个PowerModeChanged事件,在电源状态发生更改时触发,例如当用户暂停或恢复操作系统,或者AC电源状态或电池状态发生变化时。 PowerStatus类的属性SystemInformation可用于查询当前状态,如下面的代码示例所示。

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;
    }
}
Public Sub New()
    InitializeComponent()
    AddHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf PowerModeChanged
End Sub

Private Sub PowerModeChanged(ByVal Sender As System.Object, ByVal e As Microsoft.Win32.PowerModeChangedEventArgs)
    Select Case SystemInformation.PowerStatus.BatteryChargeStatus
        Case BatteryChargeStatus.Low
            MessageBox.Show("Battery is running low.", "Low Battery", MessageBoxButtons.OK, _
                            System.Windows.Forms.MessageBoxIcon.Exclamation)
        Case BatteryChargeStatus.Critical
            MessageBox.Show("Battery is critically low.", "Critical Battery", MessageBoxButtons.OK, _
                            System.Windows.Forms.MessageBoxIcon.Stop)
        Case Else
            ' Battery is okay.
            Exit Select
    End Select
End Sub

BatteryChargeStatus属性除了PowerStatus枚举之外,还包含用于确定电池容量(BatteryFullLifetime)和电池充电百分比(BatteryLifePercentBatteryLifeRemaining)的枚举。

使用 SetSuspendStateApplication 方法来将计算机置于挂起或休眠模式。 force如果参数设置为false,作系统会将事件广播给请求暂停权限的所有应用程序。 如果参数 disableWakeEvent 设置为 true,则作系统将禁用所有唤醒事件。

下面的代码示例演示如何将计算机置于休眠状态。

if (SystemInformation.PowerStatus.BatteryChargeStatus == System.Windows.Forms.BatteryChargeStatus.Critical)
{
    Application.SetSuspendState(PowerState.Hibernate, false, false);
}
If SystemInformation.PowerStatus.BatteryChargeStatus = System.Windows.Forms.BatteryChargeStatus.Critical Then
    Application.SetSuspendState(PowerState.Hibernate, False, False)
End If

另请参阅