我是否需要SE_SHUTDOWN_NAME权限才能注销用户?

时间:2012-10-31 22:20:14

标签: c++ winapi logoff

我需要从C ++程序注销用户。我使用ExitWindowsEx API,但我不确定文档中是否需要任何特殊权限?

1 个答案:

答案 0 :(得分:0)

你这样做。这是一个例子

bool ShutdownWindows(void)
{
HANDLE hToken = NULL; 
TOKEN_PRIVILEGES tkp = {0};
bool bRet = false;

// Get a token for this process. 
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
    if (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. 
        if (AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, 0)) {
            ::CloseHandle(hToken);

            if (ERROR_SUCCESS == GetLastError()) {

                DWORD dwFlags = EWX_POWEROFF;
                DWORD dwReason = SHTDN_REASON_MAJOR_SYSTEM;

                if (ExitWindowsEx(dwFlags, dwReason)) {
                    bRet = true;
                }
            }
        }
    }
}

return bRet; 

} // ShutdownWindows