BOOL Util_Shutdown(int nFlag, int nReason) { /* flags can be a combination of: #define EWX_LOGOFF 0 #define EWX_SHUTDOWN 0x00000001 #define EWX_REBOOT 0x00000002 #define EWX_FORCE 0x00000004 #define EWX_POWEROFF 0x00000008 // need EWX_SHUTDOWN: now obsolete when using InitiateSystemShutdownEx() #define EWX_FORCEIFHUNG 0x00000010 */ HANDLE hToken; TOKEN_PRIVILEGES tkp; // If we are running NT, make sure we have rights to shutdown // Get a token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return FALSE; // Don't have the rights // Get the LUID for the shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; /* one privilege to set */ tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); // Cannot test the return value of AdjustTokenPrivileges. if (GetLastError() != ERROR_SUCCESS) return FALSE; // Don't have the rights // for suspend and hibernate code if ( (nFlag == 32) || (nFlag == 64) ) return SetSystemPowerState( (nFlag == 32), FALSE); // Handle logging off the user. This does not shutdown the machine. if ((nFlag & (EWX_SHUTDOWN|EWX_REBOOT|EWX_POWEROFF)) == 0) return ExitWindowsEx(nFlag, 0); BOOL bForceAppsClosed = FALSE; if (nFlag & (EWX_FORCE|EWX_FORCEIFHUNG)) bForceAppsClosed = TRUE; BOOL bRebootAfterShutdown = FALSE; if (nFlag & EWX_REBOOT) bRebootAfterShutdown = TRUE; // Shutdown or restart the machine. return InitiateSystemShutdownEx(NULL, NULL, 0, bForceAppsClosed, bRebootAfterShutdown, nReason); } // Util_Shutdown()
Edit: Updated to the 3.3.8.1 version of the code since it has changed slightly over the years.
Edited by Valik, 30 January 2012 - 07:38 PM.




