How to detect whether Vista UAC is enabled?

后端 未结 8 1292
渐次进展
渐次进展 2021-01-31 04:48

I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user\'s computer?

8条回答
  •  [愿得一人]
    2021-01-31 05:18

    You don't want to check if UAC is enabled; that doesn't tell you anything.

    I can be a standard user with UAC disabled.

    You want to check if the user is running with administrative privileges using CheckTokenMembership:

    ///This function tells us if we're running with administrative permissions.
    function IsUserAdmin: Boolean;
    var
        b: BOOL;
        AdministratorsGroup: PSID;
    begin
        {
            This function returns true if you are currently running with 
                   admin privileges.
            In Vista and later, if you are non-elevated, this function will 
                   return false (you are not running with administrative privileges).
            If you *are* running elevated, then IsUserAdmin will return 
                   true, as you are running with admin privileges.
    
            Windows provides this similar function in Shell32.IsUserAnAdmin.
                   But the function is depricated, and this code is lifted from the 
                   docs for CheckTokenMembership: 
                   http://msdn.microsoft.com/en-us/library/aa376389.aspx
        }
    
        {
            Routine Description: This routine returns TRUE if the caller's
            process is a member of the Administrators local group. Caller is NOT
            expected to be impersonating anyone and is expected to be able to
            open its own process and process token.
            Arguments: None.
            Return Value:
                TRUE - Caller has Administrators local group.
                FALSE - Caller does not have Administrators local group.
        }
        b := AllocateAndInitializeSid(
                SECURITY_NT_AUTHORITY,
                2, //2 sub-authorities
                SECURITY_BUILTIN_DOMAIN_RID,    //sub-authority 0
                DOMAIN_ALIAS_RID_ADMINS,        //sub-authority 1
                0, 0, 0, 0, 0, 0,               //sub-authorities 2-7 not passed
                AdministratorsGroup);
        if (b) then
        begin
            if not CheckTokenMembership(0, AdministratorsGroup, b) then
             b := False;
            FreeSid(AdministratorsGroup);
        end;
    
        Result := b;
    end;
    

提交回复
热议问题