#define RTN_ERROR 13
void PERR(LPTSTR szAPI, DWORD dwLastError) //休眠时调用到的一个函数,用来
////记录休眠中遇到的错误
{
LPTSTR MessageBuffer;
DWORD dwBufferLength;
fprintf(stderr,"%s error! (rc=%lu)\n", szAPI, dwLastError);
if(dwBufferLength=FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwLastError,
LANG_NEUTRAL,
(LPTSTR) &MessageBuffer,
0,
NULL))
{
DWORD dwBytesWritten;
WriteFile(GetStdHandle(STD_ERROR_HANDLE),
MessageBuffer,
dwBufferLength,
&dwBytesWritten,
NULL);
LocalFree(MessageBuffer);
}
}
INT SetPower()有//主要功能函数
{
TOKEN_PRIVILEGES tp;
HANDLE hToken;
LUID luid;
LPTSTR MachineName=NULL;
if(!OpenProcessToken(GetCurrentProcess(), ////////从这里////////////////////////////
TOKEN_ADJUST_PRIVILEGES,
&hToken ))
{
PERR("OpenProcessToken", GetLastError() );
return RTN_ERROR;
}
if(!LookupPrivilegeValue(MachineName, SE_SHUTDOWN_NAME, &luid))
{
PERR("LookupPrivilegeValue", GetLastError() );
return RTN_ERROR;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
NULL, NULL ); ////////////////到这里,是取得权限//////////////////////
SetSystemPowerState(FALSE,TRUE);
return 0;
}
这样,在任意需要休眠的时候调用SetPower();即可休眠,但是有一点要注意:必须打开了高级电源管理的休眠支持。
文章来源于领测软件测试网 https://www.ltesting.net/