/// <summary> /// 授予当前进程需要申请的Windows操作系统权限。 /// </summary> /// <param name="privilegeName">需要申请的权限所对应的权限字符串,该字符串是PrivilegeConst中包含的字符串常量。</param> /// <returns>如果操作成功,则将会返回true,否则返回false。</returns> public static bool GrantPrivilege(string privilegeName) { try { SLocallyUniqueIdentifier locallyUniqueIdentifier = new SLocallyUniqueIdentifier(); if (LookupPrivilegeValue(null, privilegeName, ref locallyUniqueIdentifier)) { SLuidAttributes luidAndAtt = new SLuidAttributes() { Attributes = (int)PrivilegeAttributes.SE_PRIVILEGE_ENABLED, ParticularLuid = locallyUniqueIdentifier }; STokenPrivileges tokenPrivileges = new STokenPrivileges() { PrivilegeCount = 1, Privileges = luidAndAtt }; STokenPrivileges tempTokenPriv = new STokenPrivileges(); IntPtr tokenHandle = IntPtr.Zero; try { bool condition = OpenProcessToken(GetCurrentProcess(), (int)TokenAccess.TOKEN_ADJUST_PRIVILEGES | (int)TokenAccess.TOKEN_QUERY, tokenHandle); if (condition) { if (AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivileges, 1024, tempTokenPriv, 0)) { if (Marshal.GetLastWin32Error() != ERROR_NOT_ALL_ASSIGNED) { return(true); } } } } finally { if (tokenHandle != IntPtr.Zero) { CloseHandle(tokenHandle); } } } return(false); } catch { return(false); } }
public static extern bool AdjustTokenPrivileges(IntPtr tokenPointer, bool disable, ref STokenPrivileges newStateInfo, Int32 bufferSize, STokenPrivileges privileges, Int32 retunValueSize);