Delphi自編寫的筆記本、台式機電源及電池屬性檢測管理代碼,可檢測電源狀態、剩余電量、剩余電池使用時間、總使用時間、啟動休眠等功能。Unit1.pas是主要文件,代碼如下:
01
unit Unit1;
02
interface
03
uses
04
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
05
StdCtrls;
06
type
07
TForm1 = class(TForm)
08
Button1: TButton;
09
Label1: TLabel;
10
Label2: TLabel;
11
Label3: TLabel;
12
Label4: TLabel;
13
Label5: TLabel;
14
Button2: TButton;
15
Label6: TLabel;
16
procedure Button1Click(Sender: TObject);
17
procedure Button2Click(Sender: TObject);
18
private
19
{ Private declarations }
20
public
21
{ Public declarations }
22
end;
23
var
24
Form1: TForm1;
25
implementation
26
{$R *.DFM}
27
procedure TForm1.Button1Click(Sender: TObject);
28
var lpsps:SYSTEM_POWER_STATUS;
29
begin
30
GetSystemPowerStatus(lpsps);
31
Case lpsps.ACLineStatus of
32
0:Label1.Caption:='電源狀態 脫機';
33
1:Label1.Caption:='電源狀態 聯機';
34
2:Label1.Caption:='電源狀態 未知';
35
end;
36
Case lpsps.BatteryFlag of
37
1: Label2.Caption:='電池狀態 高';
38
2: Label2.Caption:='電池狀態 低';
39
4: Label2.Caption:='電池狀態 臨界';
40
8: Label2.Caption:='電池狀態 充電';
41
128:Label2.Caption:='電池狀態 無系統電池';
42
255:Label2.Caption:='電池狀態 未知';
43
end;
44
Case lpsps.BatteryLifePercent of
45
0..100:Label3.Caption:='剩余電池 '+IntToStr(lpsps.BatteryLifePercent*100)+'%';//注意選擇標志的用法
46
255: Label3.Caption:='剩余電池 未知';
47
end;
48
If lpsps.BatteryLifeTime=$FFFFFFFF Then
49
Label4.Caption:='電池剩余時間 未知'
50
Else
51
Label4.Caption:='電池剩余時間 '+IntToStr(lpsps.BatteryLifeTime)+'秒';
52
If lpsps.BatteryFullLifeTime=$FFFFFFFF Then
53
Label5.Caption:='電池總使用時間 未知'
54
Else
55
Label5.Caption:='電池總使用時間 '+IntToStr(lpsps.BatteryFullLifeTime)+'秒';
56
end;
57
procedure TForm1.Button2Click(Sender: TObject);
58
begin
59
If SetSystemPowerState(false,false)=true then
60
Label6.Caption:='成功休眠'
61
Else
62
Label6.Caption:='不支持休眠或休眠失敗';
63
end;
64
end.
編譯後運行,可看到如下程序界面:
