Battery Status Monitoring in C#
(베터리 상태 체크하기)



Intro

 딸내미가 Battery 상태 Check 하는 방법에 대해서 물어봐서 블로깅을 할까 합니다. =_=
베터리를 체크하는 방법은 매우 간단합니다.
물론 C# 에서 말이죠.

이유는 하나 입니다.
PowerStatus 라는 클래스가 제공되기 때문입니다. -_-
블로깅 하기 뭐하지만 여튼 코드를 살펴보도록 하겠습니다.


Contents

우선 MSDN 에서 PowerStatus 라는 녀석을 찾아봅시다.
http://msdn.microsoft.com/ko-kr/library/system.windows.forms.powerstatus(v=VS.90)




유심히 봐야 하는 부분은 네임스페이스 입니다.
System.Windows.Forms 안에 있습니다.

그리고 매우 중요한 것 한가지.
PowerStatus 는 생성자가 제공되지 않습니다.
SystemInformation.PowerStatus 를 통해 가져올 수 있습니다.


PowerStatus 클래스에 어떤 것들이 있는지 멤버를 확인해 봅니다.


MSDN 에서 보시면 아시겠지만, 메서드는 특별히 제공되는게 없습니다.
전부 프로퍼티들 입니다. 그냥 가져다 쓰기만 하면 된다라는 것이죠.
물론 이벤트도 없습니다. 위에 보이는 속성(프로퍼티)이 전부입니다.


enum 타입인 BatteryChargeStatus 의 멤버는 아래와 같습니다.



설명에 나와 있듯이, BatteryFullLifetimeint 형이며, 만충되었을 때 베터리의 수명(초) 입니다.
알 수 없는 경우에는 -1 이 리턴된다고 되어 있습니다.

마찬가지로 BatteryLifePercentfloat 형이며, 0 부터 1.0 사이값이 리턴됩니다.
알 수 없는 경우에는 255 가 리턴됩니다.

BatteryLifeRemaining int 형이며, 현재 남아있는 베터리의 시간(초) 입니다.
알 수 없는 경우에는 -1 이 리턴됩니다.

마지막으로 PowerLineStatusenum 타입이며, 멤버는 아래와 같습니다.


만약 전원이 케이블로 공급되고 있다면, Online 이고 그렇지 않다면 Offline 이겠지요.



Code

 이 Class 를 가지고 간단한 프로그램을 만들어 보도록 하겠습니다.
베터리 상태를 일정 주기로 체크해서 화면에 보여줍니다.

프로그램 실행시 화면입니다.







5 초 주기로 배터리 상태를 화면에 출력해 줍니다. 실제로는 1분 간격으로 해도 충분하겠죠. 테스트를 위해 5초로 하였습니다.
아이콘은 전원케이블/베터리/잔여량 정도에 따라 변경됩니다.

코드는 아래와 같습니다.


public partial class MainForm : Form
{
    private Timer MonitorTimer = new Timer();
    
    
    public MainForm() {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);

        this.MonitorTimer.Interval = 5000; // 5초에 한번씩 상태를 체크
        this.MonitorTimer.Tick += new EventHandler(MonitorTimer_Tick);
        this.MonitorTimer.Start();
        // 최초 호출
        this.UpdateText();
        this.UpdateIcon();
    }


    protected override void OnClosing(CancelEventArgs e) {
        base.OnClosing(e);
        this.MonitorTimer.Stop();
    }


    void MonitorTimer_Tick(object sender, EventArgs e) {
        this.UpdateText();
        this.UpdateIcon();
    }


    private void UpdateText() {
        PowerStatus status = SystemInformation.PowerStatus;

        this.lblChargeStatus.Text = status.BatteryChargeStatus.ToString();
        this.lblFullLifeTime.Text = (status.BatteryFullLifetime != -1 ? status.BatteryFullLifetime.ToString() : "-");
        this.lblPowerStatus.Text = status.PowerLineStatus.ToString();
        this.lblRemainLifeTime.Text = (status.BatteryLifeRemaining != -1 ? TimeSpan.FromSeconds(status.BatteryLifeRemaining).ToString() : "-");
        this.progBarPower.Value = (int)(status.BatteryLifePercent != 255 ? status.BatteryLifePercent * 100 : 0);
    }


    private void UpdateIcon() {
        PowerStatus status = SystemInformation.PowerStatus;
        if (status.PowerLineStatus == PowerLineStatus.Offline) {
            if (status.BatteryLifePercent > 0.5) {
                this.picBoxPower.Image = PowerMonitor.Resource1.BatteryGreen;
            } else {
                this.picBoxPower.Image = PowerMonitor.Resource1.BatteryRed;
            }
        } else if (status.PowerLineStatus == PowerLineStatus.Online) {
            this.picBoxPower.Image = PowerMonitor.Resource1.PowerGreen;
        } else if(status.PowerLineStatus == PowerLineStatus.Unknown) {
            this.picBoxPower.Image = PowerMonitor.Resource1.unkown;
        }
    }
}



프로그램과 소스는 아래에서 받으시면 됩니다.

PowerMonitor.exe

PowerMonitor.zip




Result

 .NET 의 경우에는 나날이 버젼이 업데이트 되고 있고, 그럴 때 마다 사용자가 필요로 하는 Class 들이 계속 증가하고 있습니다. 다시 말하자면 여러분이 원하는 일을 해 주는 Class 는 대부분 이미 만들어져 있다라는 이야기입니다. :)