获取UserPrincipalName

Avatar photo
Private Declare PtrSafe Function GetUserNameEx Lib "secur32.dll" Alias "GetUserNameExA" ( _
    ByVal nameFormat As Long, _
    ByVal nameBuffer As String, _
    ByRef nameSize As Long) As Long
 
Private Declare PtrSafe Function TranslateName Lib "secur32.dll" Alias "TranslateNameA" ( _
    ByVal lpName As String, _
    ByVal nameFormat As Long, _
    ByVal desiredFormat As Long, _
    ByVal translatedName As String, _
    ByRef lpnLength As Long) As Long
 
Private Const NAME_FORMAT_USER_PRINCIPAL_NAME = &H2
Private Const TRANSLATED_NAME_FORMAT_CANONICAL = &H1
Private Const TRANSLATED_NAME_USER_PRINCIPAL = &H8
 
Public Function GetUserPrincipalName() As String
    Dim userNameBuffer As String * 256
    Dim userNameSize As Long
    Dim translatedNameBuffer As String * 256
    Dim translatedNameSize As Long
    Dim result As Long
    
    userNameSize = 256
    result = GetUserNameEx(NAME_FORMAT_USER_PRINCIPAL_NAME, userNameBuffer, userNameSize)
    
    If result Then
        translatedNameSize = 256
        result = TranslateName(userNameBuffer, NAME_FORMAT_USER_PRINCIPAL_NAME, TRANSLATED_NAME_USER_PRINCIPAL, translatedNameBuffer, translatedNameSize)
        
        If result Then
            GetUserPrincipalName = Left$(translatedNameBuffer, InStr(translatedNameBuffer, Chr$(0)) - 1)
        Else
            GetUserPrincipalName = ""
        End If
    Else
        GetUserPrincipalName = ""
    End If
End Function

Public Sub show()
    MsgBox GetUserPrincipalName
End Sub

测试成功,可以显示用户邮箱格式的User Principal Name

参考文献:

用户命名属性 – Win32 apps | Microsoft Learn api查看

EXTENDED_NAME_FORMAT (secext.h) – Win32 apps | Microsoft Learn 翻译方法的参数