Ejemplo n.º 1
0
 static extern bool AdjustTokenPrivileges(
     IntPtr tokenHandle,
     [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
     ref TOKEN_PRIVILEGES1 newState,
     UInt32 null1,
     IntPtr zero1,
     IntPtr zero2);
Ejemplo n.º 2
0
        public static bool SetPrivilege(IntPtr hToken, string lpszPrivilege, bool bEnablePrivilege)
        {
            const uint ERROR_NOT_ALL_ASSIGNED = 1300;
            const uint SE_PRIVILEGE_ENABLED   = 0x2;

            var luid = new LUID();

            if (!LookupPrivilegeValue(null, lpszPrivilege, ref luid))
            {
                System.Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return(false);
            }

            var tp = new TOKEN_PRIVILEGES1 {
                PrivilegeCount = 1,
                Privileges     =
                {
                    Luid       = luid,
                    Attributes = bEnablePrivilege ? (int)SE_PRIVILEGE_ENABLED : 0
                }
            };

            // Enable the privilege or disable all privileges.
            if (!AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
            {
                var err = Marshal.GetLastWin32Error();
                switch (err)
                {
                case (int)ERROR_NOT_ALL_ASSIGNED:
                    System.Console.WriteLine("The token does not have the specified privilege.");
                    return(false);

                default:
                    System.Console.WriteLine(new Win32Exception(err).Message);
                    return(false);
                }
            }
            return(true);
        }