Windows设置系统关机/重启

2019-08-27  本文已影响0人  Virtualer

执行某些操作之后需要系统关机或者重启,个人一直采用此种方式进行操作。

直接上代码:

int ExReBoot(int Type, BOOL fForce)
{//Type 0 重启,1 关机
       HANDLE hToken;
       TOKEN_PRIVILEGES tkp;
       // Get a token for this process.
       if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
       {
              OutputDebugString("OpenProcessToken failed");
              return -1;
       }
       // 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)
       {
              OutputDebugString("AdjustTokenPrivileges failed");
              return -1;
       }
       if (Type == 1)
       {
              if (fForce == TRUE)
                     ExitWindowsEx(EWX_POWEROFF | EWX_SHUTDOWN | EWX_FORCE, 0);
              else
                     ExitWindowsEx(EWX_POWEROFF | EWX_SHUTDOWN, 0);
       }
       else
       {
              if (fForce == TRUE)
                     ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0);
              else
                     ExitWindowsEx(EWX_REBOOT, 0);
       }
       return 1;
}
上一篇 下一篇

猜你喜欢

热点阅读