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

本文介绍了一种使用C#和VB获取系统电源状态的方法,通过调用GetSystemPowerState函数,可以检查设备是否处于开机、关机、待机等不同状态。文章提供了详细的代码示例。
  今天在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值