internal static extern bool AdjustTokenPrivileges( IntPtr TokenHandle, bool DisableAllPrivileges, ref _TOKEN_PRIVILEGES NewState, uint NewStateLength, IntPtr PreviousState, IntPtr PreviousStateLength);
public static extern Boolean AdjustTokenPrivileges( IntPtr TokenHandle, Boolean DisableAllPrivileges, ref _TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, ref _TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes );
public static void EnablePrivilege(string Privilege) { // Original code: https://www.leeholmes.com/blog/2010/09/24/adjusting-token-privileges-in-powershell/ // GO Lang implementation: https://stackoverflow.com/a/55304787 _TOKEN_PRIVILEGES tp = new _TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new _LUID_AND_ATTRIBUTES { Attributes = SE_PRIVILEGE_ENABLED // or SE_PRIVILEGE_DISABLED if you want to disable // all privileges. } }; IntPtr ProcesHandle = Process.GetCurrentProcess().Handle; IntPtr TokenHandle = IntPtr.Zero; Console.WriteLine("Requesting: " + Privilege); if (OpenProcessToken( ProcesHandle, // HANDLE ProcessHandle TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, // DWORD DesiredAccess ref TokenHandle)) // PHANDLE TokenHandle { if (LookupPrivilegeValue( null, // LPCSTR lpSystemName Privilege, // LPCSTR lpName out tp.Privileges.Luid)) // PLUID lpLuid { if (AdjustTokenPrivileges( TokenHandle, // HANDLE TokenHandle false, // BOOL DisableAllPrivileges ref tp, // PTOKEN_PRIVILEGES NewState 0, // DWORD BufferLength IntPtr.Zero, // PTOKEN_PRIVILEGES PreviousState IntPtr.Zero)) // PDWORD ReturnLength { Console.WriteLine("Received : " + Privilege); return; } } } Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); }