public static bool SetProcessPrivilege(string privilege, bool newState, out bool previousState) { bool flag = false; previousState = false; bool result; try { IntPtr zero = IntPtr.Zero; NativeMethods.LUID luid = default(NativeMethods.LUID); luid.LowPart = 0U; luid.HighPart = 0U; if (!NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess(), TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges, ref zero)) { result = false; } else if (!NativeMethods.LookupPrivilegeValue(null, privilege, ref luid)) { NativeMethods.CloseHandle(zero); result = false; } else { NativeMethods.TOKEN_PRIVILEGE token_PRIVILEGE = default(NativeMethods.TOKEN_PRIVILEGE); NativeMethods.TOKEN_PRIVILEGE token_PRIVILEGE2 = default(NativeMethods.TOKEN_PRIVILEGE); token_PRIVILEGE.PrivilegeCount = 1U; token_PRIVILEGE.Privilege.Luid = luid; token_PRIVILEGE.Privilege.Attributes = (newState ? 2U : 0U); uint num = 0U; NativeMethods.AdjustTokenPrivileges(zero, false, ref token_PRIVILEGE, (uint)Marshal.SizeOf(token_PRIVILEGE2), ref token_PRIVILEGE2, ref num); previousState = ((token_PRIVILEGE2.Privilege.Attributes & 2U) > 0U); flag = true; NativeMethods.CloseHandle(zero); result = flag; } } catch (Exception) { result = flag; } return(result); }
private static extern bool LookupPrivilegeValue([In] string lpSystemName, [In] string lpName, [In][Out] ref NativeMethods.LUID Luid);