1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
   | #If VBA7 Then
    Declare PtrSafe  Function LogonUser Lib "advapi32" Alias "LogonUserA" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Long, ByVal dwLogonProvider As Long, phToken As Long) As Long
    Declare PtrSafe  ImpersonateLoggedOnUser Lib "advapi32.dll" (ByVal hToken As Long) As Long
    Declare PtrSafe  RevertToSelf Lib "advapi32.dll" () As Long
#Else
    Public Declare Function LogonUser Lib "advapi32" Alias "LogonUserA" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Long, ByVal dwLogonProvider As Long, phToken As Long) As Long
    Declare Function ImpersonateLoggedOnUser Lib "advapi32.dll" (ByVal hToken As Long) As Long
    Declare Function RevertToSelf Lib "advapi32.dll" () As Long
#End If
Enum MConst
    LOGON32_LOGON_INTERACTIVE = 2
    LOGON32_PROVIDER_DEFAULT = 0
End Enum
Public lngTokenHandle, lngLogonType, lngLogonProvider As Long
Public blnResult As Boolean
 
 
Sub TEST()
 If AdminLogOn("Username", "Domain", "Password") Then
    Shell "C:\Windows\System32\calc.exe"
    Shell "C:\Windows\system32\notepad.exe"
 Logoff
 End If
End Sub
 
 
Public Function AdminLogOn(Username, Domain, Password) As Boolean
blnResult = RevertToSelf()
If LogonUser( _
Username, _
Domain, _
Password, _
          LOGON32_LOGON_INTERACTIVE, _
         LOGON32_PROVIDER_DEFAULT, _
            lngTokenHandle) = 0 Then
    MsgBox "Impossible d'ouvrir la session : " & Username & ". "
    GoTo Fin
End If
 
 
 
 
If blnResult = False Then
    MsgBox "Impossible d'ouvrir LogonUser"
   GoTo Fin
End If
 
 
blnResult = ImpersonateLoggedOnUser(lngTokenHandle)
AdminLogOn = True: Exit Function
 
 
Fin:
AdminLogOn = False
End Function
Public Sub Logoff()
Dim blnResult As Boolean
'MsgBox "Session fermée"
blnResult = RevertToSelf()
End Sub | 
Partager