ExitWindowsEx 关机、重启、注销的编程实现

来自http://tunps.com/exitwindowsex

如果是win98及其之前的系统没有很好的安全性和权限管理机制,ExitWindowsEx 可以在任意权限下执行,而之后的系统则需要提升权限后才能在调用ExitWindowsEx之后成功返回。

实例代码,运行后,重启动,在winxp sp3、win 7 ultimate administrator默认权限下测试成功:

#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken))
    {
        LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
        ExitWindowsEx(EWX_REBOOT, 0);
    }
    return 0;
}

OpenProcessToken的作用得到当前进程的access token。

LookupPrivilegeValue 得到指定权限的LUID。

AdjustTokenPrivileges 在指定的access token上打开或关闭特定权限,需要 TOKEN_ADJUST_PRIVILEGES 权限来访问。

ExitWindowsEx Logs off the interactive user, shuts down the system, or shuts down and restarts the system. It sends the WM_QUERYENDSESSION message to all applications to determine if they can be terminated.

About tunpishuang

just 4 fun·····
This entry was posted in 未分类 and tagged , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>