1 #include <powrprof.h> 2 #pragma comment(lib,"PowrProf.lib") 3 4 5 // 该函数没有InitiateSystemShutdown强大,主要是只能关本机 6 // ExitWindowsEx( EWX_FORCE | EWX_POWEROFF, 0 ); 7 // 此函数为休眠, 但已不推荐 8 // SetSystemPowerState(FALSE,TRUE); 9 BOOL PowerManage( int nOpType, UINT nSecs ) 10 { 11 HANDLE hToken; 12 TOKEN_PRIVILEGES tkp; 13 14 memset( &tkp, 0, sizeof( TOKEN_PRIVILEGES ) ); 15 16 // 获得进程访问令牌的句柄 17 if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ) 18 { 19 ::MessageBox( NULL, TEXT( "无法获得访问句柄" ), TEXT( "错误" ), MB_OK ); 20 return FALSE; 21 } 22 23 // 查看系统权限的特权值 24 if ( !LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid ) ) 25 { 26 ::MessageBox( NULL, TEXT( "无法获得特权值" ), TEXT( "错误" ), MB_OK ); 27 return FALSE; 28 } 29 30 // 使能该特权 31 tkp.PrivilegeCount = 1; 32 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 33 34 if ( !AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, ( PTOKEN_PRIVILEGES )NULL, 0 ) ) 35 { 36 ::MessageBox( NULL, TEXT( "无法使能特权" ), TEXT( "错误" ), MB_OK ); 37 return FALSE; 38 } 39 40 41 if ( nOpType == 0 && \ 42 !InitiateSystemShutdown( NULL, TEXT( "即将关机!!" ), nSecs, TRUE, FALSE ) ) 43 { 44 ::MessageBox( NULL, TEXT( "关机操作失败" ), TEXT( "错误" ), MB_OK ); 45 goto err_exit; 46 } 47 else if ( nOpType == 1 && \ 48 !InitiateSystemShutdown( NULL, TEXT( "即将重启!!" ), nSecs, TRUE, TRUE ) ) 49 { 50 ::MessageBox( NULL, TEXT( "重启操作失败" ), TEXT( "错误" ), MB_OK ); 51 goto err_exit; 52 } 53 else if ( nOpType == 2 && !SetSuspendState( FALSE, TRUE, FALSE ) ) 54 { 55 ::MessageBox( NULL, TEXT( "待机操作失败" ), TEXT( "错误" ), MB_OK ); 56 goto err_exit; 57 } 58 else if ( nOpType == 3 && !SetSuspendState( TRUE, TRUE, FALSE ) ) 59 { 60 ::MessageBox( NULL, TEXT( "休眠操作失败" ), TEXT( "错误" ), MB_OK ); 61 goto err_exit; 62 } 63 64 // 恢复此特权使能情况 65 tkp.Privileges[0].Attributes = 0; 66 AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, ( PTOKEN_PRIVILEGES )NULL, 0 ); 67 return TRUE; 68 69 err_exit: 70 71 tkp.Privileges[0].Attributes = 0; 72 AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, ( PTOKEN_PRIVILEGES )NULL, 0 ); 73 return FALSE; 74 }