lalli
lalli

Reputation: 6303

How to Reboot Programmatically?

How can I reboot in c++? Is there any provision in WinSDK? What kind of rights should my program(process) have to do so?

Upvotes: 9

Views: 13356

Answers (4)

SomeSimpleton
SomeSimpleton

Reputation: 442

@Anders solution would look, Not sure if this is fully functional as I wrote this a while ago and have not run it in a while. Documentation below.

https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges

https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegevaluea

https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdowna

void shutSystemOff(const bool &shutReboot = true)
{
    // Create all required variables
    int vRet = 0;
    bool adjustRet;
    HANDLE hToken = NULL;
    LUID luid;
    TOKEN_PRIVILEGES tp;

    // Get LUID for current boot for current process.
    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken);
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &luid);

    // Modify and Adjust token privileges for current process.
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    adjustRet = AdjustTokenPrivileges(hToken, false, &tp, sizeof(tp), NULL, 0);

    // Check if token privileges were set.
    if (adjustRet)
    {
        // Initiates system shutdown ( Local system, Shutdown Message, Dwell time, Prompt user, Reboot )
        InitiateSystemShutdownA(NULL, NULL, 0, true, shutReboot);
    }
}

Upvotes: 1

Anders
Anders

Reputation: 101559

Before calling the ExitWindowsEx function you need to enable the SE_SHUTDOWN_NAME privilege:

  1. OpenProcessToken(GetCurrentProcess (),TOKEN_ADJUST_PRIVILEGES,...)
  2. LookupPrivilegeValue
  3. AdjustTokenPrivileges
  4. CloseHandle

Upvotes: 9

johnsyweb
johnsyweb

Reputation: 141770

I presume you have a very good case for wanting to reboot a PC that may be running lots of other applications.

It sounds like you are looking for InitiateShutdown(), passing SHUTDOWN_RESTART in dwShutdownFlags.

Upvotes: 5

Den
Den

Reputation: 16826

There is the ExitWindowsEx Function that can do this. You need to pass the EWX_REBOOT (0x00000002) flag to restart the system.

Important note here (quote from MSDN):

The ExitWindowsEx function returns as soon as it has initiated the shutdown process. The shutdown or logoff then proceeds asynchronously. The function is designed to stop all processes in the caller's logon session. Therefore, if you are not the interactive user, the function can succeed without actually shutting down the computer. If you are not the interactive user, use the InitiateSystemShutdown or InitiateSystemShutdownEx function.

You can choose between the appropriate function depending on your situation.

Upvotes: 14

Related Questions