6

コンピューターのバッテリー レベルの監視に依存するプログラムを設計しています。

これは私が使用しているC#コードです:

   PowerStatus pw = SystemInformation.PowerStatus;

   if (pw.BatteryLifeRemaining >= 75)
   {
       //Do stuff here
   }

ステートメントの試行に失敗しwhileました。望ましくないすべての CPU を使用します。

    int i = 1;
    while (i == 1)
    {
        if (pw.BatteryLifeRemaining >= 75)
        {
           //Do stuff here
        }
    }

75% に達したときに何らかのコードを実行するように、無限ループでこれを常に監視するにはどうすればよいですか。

4

3 に答える 3

11

タイマーを試す:

public class Monitoring
{
    System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();

    public Monitoring()
    {
        timer1.Interval = 1000; //Period of Tick
        timer1.Tick += timer1_Tick;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        CheckBatteryStatus(); 
    }
    private void CheckBatteryStatus()
    {
        PowerStatus pw = SystemInformation.PowerStatus;

        if (pw.BatteryLifeRemaining >= 75)
        {
            //Do stuff here
        }
    }
}

アップデート:

タスクを完了する別の方法があります。使用できますSystemEvents.PowerModeChanged。それを呼び出して変更を待ち、発生した変更を監視してから作業を行います。

static void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
    if (e.Mode == Microsoft.Win32.PowerModes.StatusChange)
    {
         if (pw.BatteryLifeRemaining >= 75)
         {
          //Do stuff here
         }
    }
}
于 2013-07-24T11:46:25.923 に答える
4

while ループにより、UI の応答が低下し、アプリケーションがクラッシュします。これは、多くの方法を使用して解決できます。以下のコード スニペットがニーズに役立つことを確認してください。

public delegate void DoAsync();

private void button1_Click(object sender, EventArgs e)
{
   DoAsync async = new DoAsync(GetBatteryDetails);
   async.BeginInvoke(null, null);
}

public void GetBatteryDetails()
{
   int i = 0;
   PowerStatus ps = SystemInformation.PowerStatus;
   while (true)
   {
     if (this.InvokeRequired)
         this.Invoke(new Action(() => this.Text = ps.BatteryLifePercent.ToString() + i.ToString()));
     else
         this.Text = ps.BatteryLifePercent.ToString() + i.ToString();

     i++;
   }
}
于 2013-07-24T12:13:43.397 に答える
2
BatteryChargeStatus.Text =  SystemInformation.PowerStatus.BatteryChargeStatus.ToString(); 
BatteryFullLifetime.Text  = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();
BatteryLifePercent.Text  = SystemInformation.PowerStatus.BatteryLifePercent.ToString();
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString();
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();

何らかの操作を実行したい場合は、これらの文字列値を整数に変換するだけです。

于 2015-07-25T20:19:27.543 に答える