He creado una aplicación que necesita estar en un estado seguro, por lo que quiero seguir el estado de alimentación de la computadora en segundo plano. Si el nivel de la batería (si existe) es bajo o crítico, no permitiría que el usuario continúe usando la aplicación y salga todo correctamente.C# - Suceso de elevación en el cambio de PowerStatus
Antes que nada, estoy asombrado de que no exista tal evento para detectar el cambio. Siempre debe verificar el PowerStatus manualmente.
Por lo tanto, he creado una envoltura alrededor de ella, algo como esto:
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);
}
}
}
}
}
pero que no funciona porque no powerstatus tiene ningún constructor público y no puedo almacenar el resultado de la anterior estado ...
¿Cómo puedo gestionar esto?
Gracias ...
¡Es por eso que estoy buscando! Gracias :) –
@Arnaud: No hay problema;) – w69rdy