VC实现windows系统强制关机重启和注销功能的代码
来源:http://blog.csdn.net/cackeme/article/details/7825751
#ifndef __H_SHUTDOWN_H__ #define __H_SHUTDOWN_H__ typedef enum _SHUTDOWN_ACTION { ShutdownNoReboot, ShutdownReboot, ShutdownPowerOff } SHUTDOWN_ACTION; typedef DWORD (WINAPI* lpNtShutdownSystem)(SHUTDOWN_ACTION Action); typedef DWORD (WINAPI* lpNtSetSystemPowerState)(IN POWER_ACTION SystemAction, IN SYSTEM_POWER_STATE MinSystemState, IN ULONG Flags); class KsSystemDown { protected: HMODULE hNtdll; TOKEN_PRIVILEGES tkp; HANDLE hToken; lpNtShutdownSystem NtShutdownSystem; lpNtSetSystemPowerState NtSetSystemPowerState; public: BOOL SystemShutdown(SHUTDOWN_ACTION action) { if (!NtShutdownSystem) return FALSE; DWORD dwRet = NtShutdownSystem(action); if (dwRet == 0) return TRUE; else return FALSE; } BOOL SystemPowerdown(IN POWER_ACTION SystemAction,IN SYSTEM_POWER_STATE MinSystemState,IN ULONG Flags) { if (!NtSetSystemPowerState) return FALSE; DWORD dwRet = NtSetSystemPowerState(SystemAction,MinSystemState,Flags); if (dwRet == 0) return TRUE; else return FALSE; } BOOL CommonLogoff() { return Shutdown(EWX_LOGOFF); } BOOL CommonShutdown() { return Shutdown((EWX_POWEROFF|EWX_SHUTDOWN)); } BOOL CommonReBoot() { return Shutdown(EWX_REBOOT); } BOOL FastLogoff() { return Shutdown(EWX_LOGOFF|EWX_FORCE); } BOOL FastShutdown() { return Shutdown(EWX_POWEROFF|EWX_SHUTDOWN|EWX_FORCE); } BOOL FastReboot() { return Shutdown(EWX_REBOOT|EWX_FORCE); } BOOL Shutdown(DWORD dwValue) { return ExitWindowsEx(dwValue,0); } BOOL SuperShutdown() { if (NtShutdownSystem != NULL) return NtShutdownSystem(ShutdownNoReboot); else return FALSE; } BOOL SuperReboot() { if (NtShutdownSystem != NULL) return NtShutdownSystem(ShutdownReboot); else return FALSE; } public: KsSystemDown(): NtShutdownSystem(NULL),NtSetSystemPowerState(NULL) { OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&hToken); LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, 0); CloseHandle(hToken); hNtdll = GetModuleHandle("ntdll.dll"); if (hNtdll) { NtShutdownSystem = (lpNtShutdownSystem)GetProcAddress(hNtdll,"NtShutdownSystem"); NtSetSystemPowerState = (lpNtSetSystemPowerState)GetProcAddress(hNtdll,"NtSetSystemPowerState"); } } ~KsSystemDown() { tkp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); } }; #endif