[CF.Skills]获取系统电源状态

 今天在Peter Foot博客上看到如何获取系统的电源状态(不是电池状态)的一篇文章,
他使用的VB描述:

<DllImport("coredll.dll")> _
PublicSharedFunction GetSystemPowerState(
ByVal pBuffer As System.Text.StringBuilder, ByVal Length AsInteger, ByRef pFlags As PowerState) AsInteger
EndFunction

<Flags()> _
PublicEnum PowerState
[
On= &H10000 '// on state
Off= &H20000 ' // no power, full off
Critical = &H40000 '// critical off
Boot = &H80000 ' // boot state
Idle = &H100000 ' // idle state
Suspend = &H200000 ' // suspend state
Unattended = &H400000 ' // Unattended state.
Reset= &H800000 ' // reset state
UserIdle = &H1000000 ' // user idle state
BackLightOn = &H2000000 ' // device screen backlight on
Password = &H10000000 ' // This state is password protected.
EndEnum


PrivateSub Button1_Click(
ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim sb AsNew System.Text.StringBuilder(260)
Dim flags As PowerState = 0
Dim ret AsInteger= GetSystemPowerState(sb, sb.Capacity, flags)

TextBox1.Text 
= sb.ToString()
TextBox2.Text 
= flags.ToString()
EndSub 

我写了一个C#的版本:

        private void menuPowerState_Click(object sender, EventArgs e)
        
{
            StringBuilder sb 
= new StringBuilder(32);
            MyRef.GetSysPowerState(sb, 
32);
        }

    [Flags]
    
public enum PowerState:uint
    
{
        
//更多的参数在Pm.h中
        POWER_STATE_ON = 0x00010000,
        POWER_STATE_OFF 
= 0x00020000,
        POWER_STATE_CRITICAL 
= 0x00040000,
        POWER_STATE_BOOT 
= 0x00080000,
        POWER_STATE_IDLE 
= 0x00100000,
        POWER_STATE_SUSPEND 
= 0x00200000,
        POWER_STATE_RESUME 
= 0x00400000,
        POWER_STATE_RESET 
= 0x00800000,
    }

    
class MyRef
    
{
        
private static PowerState state = 0;
        [DllImport(
"Coredll.dll", SetLastError = true)]
        
public static extern void GetSystemPowerState(StringBuilder sb, uint length, ref PowerState ps);

        
public static void GetSysPowerState(StringBuilder sb, uint length)
        
{
            GetSystemPowerState(sb, length, 
ref state);
            MessageBox.Show(String.Format(
"Is devive power on? {0}",(state&PowerState.POWER_STATE_ON)==PowerState.POWER_STATE_ON));
        }

    }

效果如下:

相当easy~

Enjoy it~

©Freesc Huang
  黄季冬<fox23>@HUST

posted on 2008-03-09 11:31  J.D Huang  阅读(2267)  评论(5编辑  收藏  举报