Programming Tips - How do I programmatically reboot Windows?

Date: 2008jan18 Platform: win32 OS: Windows Language: C/C++ Q. How do I programmatically reboot Windows? A. Here's how:
#ifndef WIN32S #define WIN32S 0x80000000l #endif BOOL PressTheResetButton() { HANDLE hToken; TOKEN_PRIVILEGES tkp; // Get a token for this process. if (!(GetVersion() & WIN32S)) { //Debug("Setting token\n"); // Running on NT or later so need to change privileges if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { Debug("OpenProcessToken error %d\n", GetLastError()); } // Get the LUID for shutdown privilege LookupPrivilegeValue(NULL, TEXT("SeShutdownPrivilege"), &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process. if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0)) { Debug("AdjustTokenPrivileges error %d\n", GetLastError()); } } // Shut down the system, and force all applications closed. if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0)) { Debug("ExitWindowsEx force error %d\n", GetLastError()); } // If we're here it didn't work return FALSE; }