判断当前进程是否以管理员程序运行的方法
通用方法,使用win32API,以下是vb6代码:
Option Explicit Private Const SECURITY_BUILTIN_DOMAIN_RID As Long = &H20 Private Const DOMAIN_ALIAS_RID_ADMINS As Long = &H220 Private Declare Function AllocateAndInitializeSid Lib "advapi32.dll" (pIdentifierAuthority As Any, ByVal nSubAuthorityCount As Byte, ByVal nSubAuthority0 As Long, ByVal nSubAuthority1 As Long, ByVal nSubAuthority2 As Long, ByVal nSubAuthority3 As Long, ByVal nSubAuthority4 As Long, ByVal nSubAuthority5 As Long, ByVal nSubAuthority6 As Long, ByVal nSubAuthority7 As Long, lpPSid As Long) As Long Private Declare Sub FreeSid Lib "advapi32.dll" (ByVal pSid As Long) Private Declare Function CheckTokenMembership Lib "advapi32.dll" (ByVal hToken As Long, ByVal pSidToCheck As Long, pbIsMember As Long) As Long Private Type SID_IDENTIFIER_AUTHORITY Value(0 To 5) As Byte End Type Private Function pvIsAdmin() As Boolean Dim uAuthNt As SID_IDENTIFIER_AUTHORITY Dim pSidAdmins As Long Dim lResult As Long uAuthNt.Value(5) = 5 If AllocateAndInitializeSid(uAuthNt, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, pSidAdmins) <> 0 Then If CheckTokenMembership(0, pSidAdmins, lResult) <> 0 Then pvIsAdmin = (lResult <> 0) End If Call FreeSid(pSidAdmins) End If End Function Private Sub Form_Load() MsgBox pvIsAdmin() End Sub
对于C#,微软有封装,比较简单,如下:
public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } private void Form1_Load(object sender, EventArgs e) { MessageBox.Show(IsAdministrator().ToString()); }
桂棹兮兰桨,击空明兮溯流光。