public static bool UacEnabled() { if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version < new Version(6, 0)) { return false; } SafeTokenHandle hToken = new SafeTokenHandle(); bool result = NativeMethods.OpenProcessToken(KernelApi.NativeMethods.GetCurrentProcess(), NativeMethods.TOKEN_QUERY, out hToken); if (!result || hToken.IsInvalid) throw KernelApi.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); IntPtr pElevationType = Marshal.AllocHGlobal(Marshal.SizeOf( typeof(NativeMethods.TOKEN_ELEVATION_TYPE))); try { uint returnSize = 0; result = NativeMethods.GetTokenInformation(hToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, sizeof(NativeMethods.TOKEN_ELEVATION_TYPE), out returnSize); if (!result) throw KernelApi.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); NativeMethods.TOKEN_ELEVATION_TYPE elevationType = (NativeMethods.TOKEN_ELEVATION_TYPE)Marshal.PtrToStructure( pElevationType, typeof(NativeMethods.TOKEN_ELEVATION_TYPE)); return elevationType != NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault; } finally { Marshal.FreeHGlobal(pElevationType); } }
public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out SafeTokenHandle TokenHandle);
public static extern bool GetTokenInformation(SafeTokenHandle TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);