42 votes

Comment puis-je détecter si mon processus exécute UAC-Elevated ou non?

Mon application Vista doit savoir si l'utilisateur l'a lancée "en tant qu'administrateur" ou en tant qu'utilisateur standard (non élevé). Comment puis-je détecter cela au moment de l'exécution?

41voto

Adrian Clark Points 7269

Pour ceux d'entre nous qui travaillent en C #, Windows SDK contient une application "UACDemo" faisant partie des "échantillons technologiques croisés". Ils trouvent si l'utilisateur actuel est un administrateur utilisant cette méthode:

 private bool IsAdministrator
{
    get
    {
        WindowsIdentity wi = WindowsIdentity.GetCurrent();
        WindowsPrincipal wp = new WindowsPrincipal(wi);

        return wp.IsInRole(WindowsBuiltInRole.Administrator);
    }
}
 

(Remarque: j'ai refactoré le code d'origine pour qu'il devienne une propriété plutôt qu'une déclaration "if")

20voto

Andrei Belogortseff Points 1096

La fonction C ++ suivante peut faire cela:

 HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );

/*
Parameters:

ptet
    [out] Pointer to a variable that receives the elevation type of the current process.

    The possible values are:

    TokenElevationTypeDefault - This value indicates that either UAC is disabled, 
        or the process is started by a standard user (not a member of the Administrators group).

    The following two values can be returned only if both the UAC is enabled
    and the user is a member of the Administrator's group:

    TokenElevationTypeFull - the process is running elevated. 

    TokenElevationTypeLimited - the process is not running elevated.

Return Values:

    If the function succeeds, the return value is S_OK. 
    If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().

Implementation:
*/

HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet )
{
    if ( !IsVista() )
        return E_FAIL;

    HRESULT hResult = E_FAIL; // assume an error occurred
    HANDLE hToken   = NULL;

    if ( !::OpenProcessToken( 
                ::GetCurrentProcess(), 
                TOKEN_QUERY, 
                &hToken ) )
    {
        return hResult;
    }

    DWORD dwReturnLength = 0;

    if ( ::GetTokenInformation(
                hToken,
                TokenElevationType,
                ptet,
                sizeof( *ptet ),
                &dwReturnLength ) )
    {
            ASSERT( dwReturnLength == sizeof( *ptet ) );
            hResult = S_OK;
    }

    ::CloseHandle( hToken );

    return hResult;
}
 

4voto

Guy Glirbas Points 11

Je ne pense pas que le type d'altitude soit la réponse que vous voulez. Vous voulez juste savoir s'il est élevé. Utilisez TokenElevation au lieu de TokenElevationType lorsque vous appelez GetTokenInformation. Si la structure renvoie une valeur positive, l'utilisateur est admin. Si zéro, l'utilisateur est l'altitude normale.

Voici une solution Delphi:

 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;
 

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X