开发者

How to Reboot Programmatically?

开发者 https://www.devze.com 2023-01-16 09:06 出处:网络
How can I reboot in c++? Is there any provision in WinSDK开发者_JAVA技巧? What kind of rights should my program(process) have to do so?There is the ExitWindowsEx Function that can do this. You need to

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


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.


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


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.


@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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消