致谢:本文档参考了,表示崇敬的谢意。
闲话不表,直接上菜。
/*
*file: WifiControl.h
*desp: power on/off wifi device by "SetDevicePower" way
*/
#ifndef _WIFICONTROL_H_
#define _WIFICONTROL_H_
#include <PM.h>
#include <Winreg.h>
class WifiControl
{
public:
/// <summary>
/// 类构造函数, 主要功能是从注册表中获取到wifi的设备描述串
/// 此串是以"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Power\State\{98C5250D-C29A-4985-AE5F-AFE5367E5006}\"打头的
/// 如果是背景灯,则直接赋 m_tsDevice 值为"TEXT("BKL1:")"
/// </summary>
WifiControl()
{
ZeroMemory(m_tsDevice, MAX_PATH);
HKEY hKey = NULL;
LPCTSTR lpSubKey=_T("System\\CurrentControlSet\\Control\\Power\\State");
LPCTSTR lpKeyValueHead = _T("{98C5250D-C29A-4985-AE5F-AFE5367E5006}\\");
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &hKey))
return;
DWORD dwIndex = 0;
DWORD dwMaxPath = MAX_PATH;
DWORD dwType = 0;
while (RegEnumValue(hKey, dwIndex++, m_tsDevice, &dwMaxPath, NULL, &dwType, NULL, NULL) != ERROR_NO_MORE_ITEMS)
{
if (NULL != wcsstr(m_tsDevice, lpKeyValueHead))
break;
ZeroMemory(m_tsDevice, MAX_PATH);
dwMaxPath = MAX_PATH;
}
::RegCloseKey(hKey);
}
/// <summary>
/// wifi设备是否开启
/// </summary>
/// <returns>TRUE:开启;FALSE:未开启</returns>
BOOL IsEnabled()
{
CEDEVICE_POWER_STATE s = D4;
if (m_tsDevice [0])
{
GetDevicePower(m_tsDevice, POWER_NAME, &s);
}
return s == D0;
}
/// <summary>
/// 给wifi设备加电或断电
/// </summary>
/// <param name="bEnable">TRUE:加电;FALSE:断电</param>
/// <returns>参考:ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/wceddk5/html/wce50lrfSetDevicePower.htm</returns>
HRESULT Enable(BOOL bEnable)
{
if (m_tsDevice [0])
{
return SetDevicePower(m_tsDevice, POWER_NAME, bEnable ? D0 : D4);
}
else
{
return ERROR_DEVICE_NOT_AVAILABLE;
}
}
protected:
WifiControl& operator=(const WifiControl&)
{}
WifiControl(const WifiControl&)
{}
private:
TCHAR m_tsDevice[MAX_PATH];
};
#endif
以上是 SetDevicePower 方式,是OK的;其实还有一种 SetPowerRequirement 方式,此种方式由电源管理器执行加电断电,电源管理器有其自身的一套供电策略,在wo的测试过程中发现:
1。如果操作WIFI,SetPowerRequirement是不行的。
2。如果操作背景灯,当灯为亮时,SetPowerRequirement断电没反应;当灯为灭时,SetPowerRequirement加电正常
以下是 SetPowerRequirement 方式的背景灯操作:
/// <summary>
/// SetPowerRequirement方式的背景灯设备加电断电,事件通知给电源管理器(power manager),由其负责执行
/// </summary>
/// <param name="bBacklightOn">布尔型,TRUE:加电;FALSE:断电</param>
void SetBacklightPowerRequirement(BOOL bBacklightOn)
{
// 背景灯设备描述串
TCHAR tszBacklightName[] = TEXT("BKL1:");
static HANDLE s_hBacklightReq = NULL;
if (bBacklightOn)
{
if (NULL == s_hBacklightReq)
{
s_hBacklightReq = SetPowerRequirement(tszBacklightName, D0, POWER_NAME | POWER_FORCE, NULL, 0);
if (!s_hBacklightReq) RETAILMSG(1, (L"SetPowerRequirement failed: %X\n", GetLastError()));
}
}
else
{
if (s_hBacklightReq)
{
if (ERROR_SUCCESS != ReleasePowerRequirement(s_hBacklightReq)) RETAILMSG(1, (L"ReleasePowerRequirement failed: %X\n", GetLastError()));
s_hBacklightReq = NULL;
}
}
}