public static class NativeMethods { [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, Int32 Zero, IntPtr Null1, IntPtr Null2); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool OpenProcessToken(IntPtr ProcessHandler, int acc, ref IntPtr ProcessToken); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LookupPrivilegeValue(string Host, string Name, ref long Luid); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool AdjustTokenPrivileges(IntPtr ProcessToken, bool disall, ref LUID Token, int Len, IntPtr prev, IntPtr ReLen); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool CloseHandle(IntPtr hObject); } [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct LUID { public int Count; public long Luid; public int Attr; } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { public LUID Luid; public UInt32 Attributes; } public struct TOKEN_PRIVILEGES { private const Int32 ANYSIZE_ARRAY = 1; public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = ANYSIZE_ARRAY)] public LUID_AND_ATTRIBUTES[] Privileges; } public static class Privileges { const int TOKEN_QUERY = 0x8; const int TOKEN_ADJUST_PRIVILEGES = 0x20; const int SE_PRIVILEGE_ENABLED = 2; public static bool SetPrivilege(IntPtr hProcess, string seName, bool enable) { bool bok = false; IntPtr hToken = IntPtr.Zero; TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(); ; LUID luid; if (!NativeMethods.LookupPrivilegeValue(string.Empty, seName, out luid)) bok = false; else { tp.PrivilegeCount = 1; tp.Privileges = new LUID_AND_ATTRIBUTES[1]; if (enable) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; if (NativeMethods.OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hToken)) { if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref tp, Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)), IntPtr.Zero, IntPtr.Zero)) bok = false; else bok = true; } else bok = false; } if (hToken != IntPtr.Zero) NativeMethods.CloseHandle(hToken); return bok; } }
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.