How can I detect if my process is running UAC-elevated or not?

后端 未结 4 1767
无人及你
无人及你 2020-12-02 18:22

My Vista application needs to know whether the user has launched it \"as administrator\" (elevated) or as a standard user (non-elevated). How can I detect that at run time?

4条回答
  •  不知归路
    2020-12-02 18:59

    I do not think elevation type is the answer you want. You just want to know if it is elevated. Use TokenElevation instead of TokenElevationType when you call GetTokenInformation. If the structure returns a positive value, the user is admin. If zero, the user is normal elevation.

    Here is a Delphi solution:

    function TMyAppInfo.RunningAsAdmin: boolean;
    var
      hToken, hProcess: THandle;
      pTokenInformation: pointer;
      ReturnLength: DWord;
      TokenInformation: TTokenElevation;
    begin
      hProcess := GetCurrentProcess;
      try
        if OpenProcessToken(hProcess, TOKEN_QUERY, hToken) then try
          TokenInformation.TokenIsElevated := 0;
          pTokenInformation := @TokenInformation;
          GetTokenInformation(hToken, TokenElevation, pTokenInformation, sizeof(TokenInformation), ReturnLength);
          result := (TokenInformation.TokenIsElevated > 0);
        finally
          CloseHandle(hToken);
        end;
      except
       result := false;
      end;
    end;
    

提交回复
热议问题