Windows フォームでの電源管理

Windows フォーム アプリケーションからは、Windows オペレーティング システムの電源管理機能を利用できます。 アプリケーションからコンピューターの電源状態を監視し、状態が変化したときにアクションを実行することができます。 たとえば、アプリケーションがポータブル コンピューター上で実行されている場合、コンピューターのバッテリ残量が特定のレベルを下回ったときに、アプリケーションの特定の機能を無効にすることができます。

.NET Framework には、ユーザーがオペレーティング システムを一時停止または再開したとき、または AC 電源の状態またはバッテリの状態が変化したときなど、電源の状態が変化するたびに発生する PowerModeChanged イベントが用意されています。 次のコード例に示すように、SystemInformation クラスの PowerStatus プロパティを使用して、現在の状態のクエリを実行することができます。

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

PowerStatus プロパティには、BatteryChargeStatus 列挙型に加え、バッテリ容量 (BatteryFullLifetime) とバッテリ残量 (BatteryLifePercentBatteryLifeRemaining) を判定する列挙型もあります。

ApplicationSetSuspendState メソッドを使用して、コンピューターを休止または一時停止モードにすることができます。 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

関連項目