如何通过Windows API关闭电脑?

Nig*_*ker 3 c++ windows winapi application-shutdown

从未编写过winapi,所以我在这里遇到了一些问题.

我需要从我的应用程序中关闭我的电脑.

我发现这个示例链接文本然后我发现这个例子如何更改权限链接文本

但我有问题如何获取该参数HANDLE hToken //访问令牌句柄

我想我需要在下一个命令中使用它来获取参数OpenProcessToken LookupPrivilegeValue AdjustTokenPrivileges但是有很多参数我不知道如何处理它们.

也许你有一些例子我如何获得HANDLE hToken参数来使其工作.

顺便说一句,我已经看到了以下帖子链接文字

非常感谢你们.

Lio*_*gan 8

// ==========================================================================
// system shutdown
// nSDType: 0 - Shutdown the system
//          1 - Shutdown the system and turn off the power (if supported)
//          2 - Shutdown the system and then restart the system
void SystemShutdown(UINT nSDType)
{
    HANDLE           hToken;
    TOKEN_PRIVILEGES tkp   ;

    ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken);
    ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

    tkp.PrivilegeCount          = 1                   ; // set 1 privilege
    tkp.Privileges[0].Attributes= SE_PRIVILEGE_ENABLED;

    // get the shutdown privilege for this process
    ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);

    switch (nSDType)
    {
        case 0: ::ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE, 0); break;
        case 1: ::ExitWindowsEx(EWX_POWEROFF|EWX_FORCE, 0); break;
        case 2: ::ExitWindowsEx(EWX_REBOOT  |EWX_FORCE, 0); break;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*cob 5

您可以使用ShellExecute()来调用shutdown.exe