Win7下VC编程设置冬眠(需要开放【SE_SHUTDOWN_NAME】权限)

BOOL SetPrivilege(
				  HANDLE hToken,          // access token handle
				  LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
				  BOOL bEnablePrivilege   // to enable or disable privilege
				  ) 
{
	TOKEN_PRIVILEGES tp;
	LUID luid;
	
	if ( !LookupPrivilegeValue( 
		NULL,            // lookup privilege on local system
		lpszPrivilege,   // privilege to lookup 
		&luid ) )        // receives LUID of privilege
	{
		printf("LookupPrivilegeValue error: %u\n", GetLastError() ); 
		return FALSE; 
	}
	
	tp.PrivilegeCount = 1;
	tp.Privileges[0].Luid = luid;
	if (bEnablePrivilege)
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	else
		tp.Privileges[0].Attributes = 0;
	
	// Enable the privilege or disable all privileges.
	
	if ( !AdjustTokenPrivileges(
		hToken, 
		FALSE, 
		&tp, 
		sizeof(TOKEN_PRIVILEGES), 
		(PTOKEN_PRIVILEGES) NULL, 
		(PDWORD) NULL) )
	{ 
		printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); 
		return FALSE; 
	} 
	
	if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
		
	{
		printf("The token does not have the specified privilege. \n");
		return FALSE;
	} 
	
	return TRUE;
}

//
// 设置【SE_SHUTDOWN_NAME】权限
//
void CTestDlg::OnButton1() 
{
	if(::MessageBox(NULL, "是否确认?", "询问", MB_ICONQUESTION|MB_YESNO) == IDNO)
		return;


	HANDLE hToken;
	BOOL bRet = OpenProcessToken(GetCurrentProcess(),TOKEN_ALL_ACCESS,&hToken);
	bRet = SetPrivilege(hToken, SE_SHUTDOWN_NAME, TRUE);
	if (!bRet)
	{
		AfxMessageBox("权限设置错误");
	}


	SetSystemPowerState(
		FALSE,	//为FASLE时悬挂;为TRUE时冬眠
		FALSE	//
		);

}

你可能感兴趣的:(Win7下VC编程设置冬眠(需要开放【SE_SHUTDOWN_NAME】权限))