• C++ 程序获取管理员权限


    VC程序获取管理员权限:

    不提示uac,直接获取管理员权限:

    在VS-项目-项目属性–连接器–清单文件–UAC执行级别改为requireAdministrator

    提示uac,用户决定是否给给予管理员权限

    开局执行函数 ElevateNow():

    BOOL IsRunAsAdministrator()
    {
    BOOL fIsRunAsAdmin = FALSE;
    DWORD dwError = ERROR_SUCCESS;
    PSID pAdministratorsGroup = NULL;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    if (!AllocateAndInitializeSid(
    &NtAuthority,
    2,
    SECURITY_BUILTIN_DOMAIN_RID,
    DOMAIN_ALIAS_RID_ADMINS,
    0, 0, 0, 0, 0, 0,
    &pAdministratorsGroup))
    {
    dwError = GetLastError();
    goto Cleanup;
    }

    if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin))
    {
    dwError = GetLastError();
    goto Cleanup;
    }

    Cleanup:

    if (pAdministratorsGroup)
    {
    FreeSid(pAdministratorsGroup);
    pAdministratorsGroup = NULL;
    }

    if (ERROR_SUCCESS != dwError)
    {
    throw dwError;
    }

    return fIsRunAsAdmin;
    }

    void ElevateNow()
    {
    BOOL bAlreadyRunningAsAdministrator = FALSE;
    try
    {
    bAlreadyRunningAsAdministrator = IsRunAsAdministrator();
    }
    catch (...)
    {

    }
    if (!bAlreadyRunningAsAdministrator)
    {
    WCHAR szPath[MAX_PATH];
    if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)))
    {


    SHELLEXECUTEINFO sei = { sizeof(sei) };

    sei.lpVerb = L"runas";
    sei.lpFile = szPath;
    sei.hwnd = NULL;
    sei.nShow = SW_SHOWDEFAULT;

    if (!ShellExecuteEx(&sei))
    {
    DWORD dwError = GetLastError();
    if (dwError == ERROR_CANCELLED)
    //Annoys you to Elevate it LOL
    CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ElevateNow, 0, 0, 0);
    }
    }

    }
    else
    {
    ///Code
    }
    }

  • 相关阅读:
    Python进阶-----类、对象的相关知识
    Python进阶-----面向对象和类的基本定义
    Python基础-----hashlib模块
    Python基础-----configparser模块
    Python基础-----logging模块
    Python基础-----re模块(模糊匹配)
    Python基础-----xml模块
    Python基础-----shelve模块
    Python基础-----pickle模块
    Python基础-----json模块
  • 原文地址:https://www.cnblogs.com/wa502/p/16392355.html
Copyright © 2020-2023  润新知