static ProcessManager() { Microsoft.Win32.NativeMethods.LUID lpLuid = new Microsoft.Win32.NativeMethods.LUID(); if (Microsoft.Win32.NativeMethods.LookupPrivilegeValue(null, "SeDebugPrivilege", out lpLuid)) { IntPtr zero = IntPtr.Zero; try { if (Microsoft.Win32.NativeMethods.OpenProcessToken(new HandleRef(null, Microsoft.Win32.NativeMethods.GetCurrentProcess()), 0x20, out zero)) { Microsoft.Win32.NativeMethods.TokenPrivileges newState = new Microsoft.Win32.NativeMethods.TokenPrivileges { PrivilegeCount = 1, Luid = lpLuid, Attributes = 2 }; Microsoft.Win32.NativeMethods.AdjustTokenPrivileges(new HandleRef(null, zero), false, newState, 0, IntPtr.Zero, IntPtr.Zero); } } finally { if (zero != IntPtr.Zero) { Microsoft.Win32.SafeNativeMethods.CloseHandle(new HandleRef(null, zero)); } } } }
private static void SetPrivilege(string privilegeName, int attrib) { IntPtr zero = IntPtr.Zero; Microsoft.Win32.NativeMethods.LUID lpLuid = new Microsoft.Win32.NativeMethods.LUID(); IntPtr currentProcess = Microsoft.Win32.NativeMethods.GetCurrentProcess(); if (!Microsoft.Win32.NativeMethods.OpenProcessToken(new HandleRef(null, currentProcess), 0x20, out zero)) { throw new Win32Exception(); } try { if (!Microsoft.Win32.NativeMethods.LookupPrivilegeValue(null, privilegeName, out lpLuid)) { throw new Win32Exception(); } Microsoft.Win32.NativeMethods.TokenPrivileges newState = new Microsoft.Win32.NativeMethods.TokenPrivileges { Luid = lpLuid, Attributes = attrib }; Microsoft.Win32.NativeMethods.AdjustTokenPrivileges(new HandleRef(null, zero), false, newState, 0, IntPtr.Zero, IntPtr.Zero); if (Marshal.GetLastWin32Error() != 0) { throw new Win32Exception(); } } finally { Microsoft.Win32.SafeNativeMethods.CloseHandle(new HandleRef(null, zero)); } }