我有一些旧代码,我们必须在VB6中维护。我们需要添加查找当前用户的 SID的功能。任何人都可以向我指出一些代码,说明如何做到这一点?在此先感谢您的帮助!
答案 0 :(得分:9)
试试这个
Option Explicit
'--- for OpenProcessToken
Private Const TOKEN_READ As Long = &H20008
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pTo As Any, uFrom As Any, ByVal lSize As Long)
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function GetTokenInformation Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long
Private Declare Function ConvertSidToStringSid Lib "advapi32.dll" Alias "ConvertSidToStringSidA" (ByVal lpSid As Long, lpString As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
Public Function GetCurrentUserSid() As String
Dim hProcessID As Long
Dim hToken As Long
Dim lNeeded As Long
Dim baBuffer() As Byte
Dim sBuffer As String
Dim lpSid As Long
Dim lpString As Long
hProcessID = GetCurrentProcess()
If hProcessID <> 0 Then
If OpenProcessToken(hProcessID, TOKEN_READ, hToken) = 1 Then
Call GetTokenInformation(hToken, 1, ByVal 0, 0, lNeeded)
ReDim baBuffer(0 To lNeeded)
'--- enum TokenInformationClass { TokenUser = 1, TokenGroups = 2, ... }
If GetTokenInformation(hToken, 1, baBuffer(0), UBound(baBuffer), lNeeded) = 1 Then
Call CopyMemory(lpSid, baBuffer(0), 4)
If ConvertSidToStringSid(lpSid, lpString) Then
sBuffer = Space(lstrlen(lpString))
Call CopyMemory(ByVal sBuffer, ByVal lpString, Len(sBuffer))
Call LocalFree(lpString)
GetCurrentUserSid = sBuffer
End If
End If
Call CloseHandle(hToken)
End If
Call CloseHandle(hProcessID)
End If
End Function
答案 1 :(得分:1)
尝试实现此功能:
Declare Function LookupAccountSid Lib "advapi32.dll" _
Alias "LookupAccountSidA" (ByVal lpSystemName As String, _
ByVal Sid As Long, ByVal Name As String, cbName As Long, _
ByVal ReferencedDomainName As String, _
cbReferencedDomainName As Long, peUse As Integer) As Long
这是实施的link。
答案 2 :(得分:0)
MSDN的一点点巡航表明NetUserGetInfo函数是您正在寻找的函数(http://msdn.microsoft.com/en-us/library/aa370654%28VS.85%29.asp x)。微软已经在这里为你写了一个例子:http://support.microsoft.com/kb/151774
答案 3 :(得分:0)
以下是a sample来自容易混淆但值得信赖的VB NET网站(在微软发明.NET之前致力于VB6)
此演示展示了如何调用 GetCurrentProcess,LookupAccountSid, AllocateAndInitializeSid, OpenProcessToken,和 GetTokenInformation以便 确定当前进程是否 在管理员下执行 帐户。这通常意味着 user是admin组的成员, 但在某些情况下(例如 作为服务运行,或者可能 指定不同于的进程 GetCurrentProcess返回的, 返回值表示是否 进程正在帐户下运行 拥有管理员权限。 (注意 插图应该说'当前 过程'而不是'用户'是最重要的 准确。)