3

从未编写过winapi,所以我在这里遇到了一个小问题。

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

我找到了这个示例链接文本然后我找到了这个示例如何更改权限链接文本

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

我想我需要按下一个顺序来获取参数 OpenProcessToken LookupPrivilegeValue AdjustTokenPrivileges 但有很多参数我不知道如何处理它们。

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

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

非常感谢你们。

4

6 回答 6

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;
    }
}
于 2009-10-01T19:29:47.517 回答
5

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

于 2009-10-01T13:19:55.533 回答
4

http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx

尝试

ExitWindowsEx(EWX_POWEROFF, 0);
于 2009-10-01T13:21:47.930 回答
4

这对于丹尼尔的回答的评论有点多,所以我会把它放在这里。

此时您的主要问题似乎是您的进程没有以执行系统关闭所需的权限运行。

ExitWindowsEx的文档包含这一行:

要关闭或重新启动系统,调用进程必须使用该 AdjustTokenPrivileges函数启用SE_SHUTDOWN_NAME权限。有关详细信息,请参阅以特殊权限运行

他们也有一些示例代码。在紧要关头,您可以复制它。

于 2009-10-01T14:00:02.707 回答
0
#include<iostream>
using namespace std;
int main(){
system("shutdown -s -f -t 0");
}
于 2014-04-12T08:07:43.337 回答
0

一些工作代码InitiateSystemShutdownEx

// Get the process token
HANDLE hToken;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
    &hToken);

// Build a token privilege request object for shutdown
TOKEN_PRIVILEGES tk;
tk.PrivilegeCount = 1;
tk.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
LookupPrivilegeValue(NULL, TEXT("SeShutdownPrivilege"), &tk.Privileges[0].Luid);

// Adjust privileges
AdjustTokenPrivileges(hToken, FALSE, &tk, 0, NULL, 0);

// Go ahead and shut down
InitiateSystemShutdownEx(NULL, NULL, 0, FALSE, FALSE, 0);

据我所知,这个ExitWindowsEx解决方案的优势在于调用进程不需要属于活动用户。

于 2014-05-01T03:36:03.310 回答