experiment: AdjustTokenPrivileges

search 'AdjustTokenPrivileges' on codeproject, find the demo all about windows control.

 

/// @file       testPrivilege.cpp
/// @brief      test Privilege enable or disable 

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <string>

BOOL EnablePrivilege(BOOL bEnable = TRUE);

int _tmain(int argc, _TCHAR* argv[])
{
    BOOL bRc = FALSE;

    bRc = EnablePrivilege(TRUE);
    _tprintf(L"%s : EnablePrivilege(TRUE)\r\n", bRc ? L"OK" : L"ERROR");

    bRc = EnablePrivilege(FALSE);
    _tprintf(L"%s : EnablePrivilege(FALSE)\r\n", bRc ? L"OK" : L"ERROR");

    _tprintf(L"\r\nEND, press any key to quit\r\n");
    getwchar();

    /** run results
    OK : EnablePrivilege(TRUE)
    OK : EnablePrivilege(FALSE)

    END, press any key to quit
    */

    return 0;
}

BOOL EnablePrivilege(BOOL bEnable)
{
    BOOL                bRc = FALSE;
    HANDLE              hToken = NULL;
    TOKEN_PRIVILEGES    tkp;

    ::ZeroMemory(&tkp, sizeof(TOKEN_PRIVILEGES));
    bRc = OpenProcessToken(
            GetCurrentProcess(),
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
            &hToken);

    if (!bRc)
        return bRc;

    if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid))
        goto _RaisePrivilege_END;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = 
        bEnable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED;

    bRc = AdjustTokenPrivileges(
            hToken,
            FALSE, 
            &tkp, 
            0, 
            (PTOKEN_PRIVILEGES)NULL, 
            0);

    if (!bRc)
        goto _RaisePrivilege_END;

    bRc = TRUE;

_RaisePrivilege_END:
    if (NULL != hToken)
        CloseHandle(hToken);

    return bRc;
}


 


你可能感兴趣的:(experiment: AdjustTokenPrivileges)