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

后端 未结 4 1762
无人及你
无人及你 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:49

    Here is a VB6 implementation of a check if a (current) process is elevated

    Option Explicit
    
    '--- for OpenProcessToken
    Private Const TOKEN_QUERY                   As Long = &H8
    Private Const TokenElevation                As Long = 20
    
    Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
    Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
    Private Declare Function GetTokenInformation Lib "advapi32" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long
    Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    
    
    Public Function IsElevated(Optional ByVal hProcess As Long) As Boolean
        Dim hToken          As Long
        Dim dwIsElevated    As Long
        Dim dwLength        As Long
    
        If hProcess = 0 Then
            hProcess = GetCurrentProcess()
        End If
        If OpenProcessToken(hProcess, TOKEN_QUERY, hToken) <> 0 Then
            If GetTokenInformation(hToken, TokenElevation, dwIsElevated, 4, dwLength) <> 0 Then
                IsElevated = (dwIsElevated <> 0)
            End If
            Call CloseHandle(hToken)
        End If
    End Function
    

提交回复
热议问题