C# - 关于PowerStatus更改的提升事件

时间:2011-03-21 13:45:29

标签: c# event-handling

我创建了一个需要处于安全状态的应用程序,所以我想在后台跟踪计算机的电源状态。如果电池电量(如果有)低或严重,我将不允许用户继续使用该应用程序并正确退出。

首先,我很惊讶没有这样的事件来检测变化。您需要始终手动检查PowerStatus。

所以,我已经创建了一个包装器,就像这样:

using System;
using System.Windows.Forms;

namespace MyApp
{
    internal static class BatteryManagement
    {
        //
        internal static event EventHandler<EventArgs> Changed;

        //
        private static bool _started;
        private static System.Threading.Timer _timer;
        private static PowerStatus _previousPowerStatus;

        internal static void Start()
        {
            if (!_started)
            {
                _started = true;
                ManageBatteryLevel();
            }
        }

        internal static void Stop()
        {
            if (_started)
            {
                if(_timer != null)
                {
                    _timer.Dispose();
                    _timer = null;
                }

                _started = false;
            }
        }

        private static void ManageBatteryLevel()
        {
            _previousPowerStatus = new PowerStatus();

            TimeSpan dueTime = new TimeSpan(0, 0, 0); // Start right now
            TimeSpan period = new TimeSpan(0, 1, 0); // Run every 1 minute

            // Setting a timer that launch every period the OnBatteryLevelChange method
            _timer = new System.Threading.Timer(OnBatteryLevelChange, null, dueTime, period);
        }

        private static void OnBatteryLevelChange(Object stateInfo)
        {
            PowerStatus powerStatus = new PowerStatus();

            if (!_previousPowerStatus.Equals(powerStatus))
            {
                // Ensure battery level is up to date before raising event
                _previousPowerStatus = powerStatus;

                if (Changed != null)
                {
                    Changed(null, EventArgs.Empty);
                }
            }
        }
    }
}

但是没有用,因为PowerStatus没有任何公共构造函数,我无法存储以前状态的结果......

我该如何管理?

谢谢...

4 个答案:

答案 0 :(得分:12)

实际上有,它被称为SystemEvents.PowerModeChanged

如果PowerModeChangedEventArgs的{​​{1}}为Mode,则表示电池状态已更改。

StatusChange

本教程也可能有用:

http://netcode.ru/dotnet/?lang=&katID=30&skatID=277&artID=7643

答案 1 :(得分:7)

如果您尝试获取当前的电源状态,则需要致电SystemInformation.PowerStatus而不是new PowerStatus()

答案 2 :(得分:2)

以下是一些代码,它们将返回PowerStatus的所有值

Type t = typeof(System.Windows.Forms.PowerStatus);            
PropertyInfo[] pi = t.GetProperties();            
for( int i=0; i<pi.Length; i++ )
{
    Console.WriteLine("Property Name {0}", pi[i].Name);
    Console.WriteLine("Property Value {0}", pi[i].GetValue(SystemInformation.PowerStatus, null));
}

希望这有帮助。

答案 3 :(得分:1)

你是对的,MSDN上的信息根本没用,你会在这里找到你需要的东西:

http://www.blackwasp.co.uk/PowerStatus.aspx

我希望它有所帮助!

相关问题