zoukankan      html  css  js  c++  java
  • Win7开发系列: Win7 UAC帮助类

    我有一个应用程序需要检测是否正在升高的特权。我现在代码建立这样的:

    函数功能 : 是否是管理员

    private static bool _isAdministrator()
    {
        WindowsIdentity identity 
    = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal 
    = new WindowsPrincipal(identity);
        
    return principal.IsInRole (WindowsBuiltInRole.Administrator);

    }

     类主要功能:

       1:UAC状态查询

       2:用户状态查询

    public static class UacHelper
    {
        
    private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
        
    private const string uacRegistryValue = "EnableLUA";

        
    private static uint STANDARD_RIGHTS_READ = 0x00020000;
        
    private static uint TOKEN_QUERY = 0x0008;
        
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);

        [DllImport(
    "advapi32.dll", SetLastError = true)]
        [
    return: MarshalAs(UnmanagedType.Bool)]
        
    static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

        [DllImport(
    "advapi32.dll", SetLastError = true)]
        
    public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);

        
    public enum TOKEN_INFORMATION_CLASS
        {
            TokenUser 
    = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin,
            TokenElevationType,
            TokenLinkedToken,
            TokenElevation,
            TokenHasRestrictions,
            TokenAccessInformation,
            TokenVirtualizationAllowed,
            TokenVirtualizationEnabled,
            TokenIntegrityLevel,
            TokenUIAccess,
            TokenMandatoryPolicy,
            TokenLogonSid,
            MaxTokenInfoClass
        }

        
    public enum TOKEN_ELEVATION_TYPE
        {
            TokenElevationTypeDefault 
    = 1,
            TokenElevationTypeFull,
            TokenElevationTypeLimited
        }

        
    public static bool IsUacEnabled
        {
            
    get
            {
                RegistryKey uacKey 
    = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
                
    bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
                
    return result;
            }
        }

        
    public static bool IsProcessElevated
        {
            
    get
            {
                
    if (IsUacEnabled)
                {
                    IntPtr tokenHandle;
                    
    if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
                    {
                        
    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                    }

                    TOKEN_ELEVATION_TYPE elevationResult 
    = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                    
    int elevationResultSize = Marshal.SizeOf((int)elevationResult);
                    
    uint returnedSize = 0;
                    IntPtr elevationTypePtr 
    = Marshal.AllocHGlobal(elevationResultSize);

                    
    bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                    
    if (success)
                    {
                        elevationResult 
    = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                        
    bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                        
    return isProcessAdmin;
                    }
                    
    else
                    {
                        
    throw new ApplicationException("Unable to determine the current elevation.");
                    }
                }
                
    else
                {
                    WindowsIdentity identity 
    = WindowsIdentity.GetCurrent();
                    WindowsPrincipal principal 
    = new WindowsPrincipal(identity);
                    
    bool result = principal.IsInRole(WindowsBuiltInRole.Administrator);
                    
    return result;
                }
            }
        }
    }

     相关资料:

       http://uachelpers.codeplex.com/releases/view/29976 

    作者:罗敏贵
    邮箱:minguiluo@163.com
    QQ群:34178394 建群 主要是寻找志同道合的人士一起学习和讨论自己的所学所思
    出处:http://luomingui.cnblogs.com/
    说明:专注于微软平台项目架构、熟悉设计模式、架构设计、敏捷个人和项目管理。现主要从事WinForm、ASP.NET、等方面的项目开发、架构、管理工作。文章为作者平时里的思考和练习,可能有不当之处,请博客园的园友们多提宝贵意见。
    知识共享许可协议本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。

  • 相关阅读:
    File
    多态
    方法重载
    Math
    instanceof
    强制类型转换
    泛型
    springboot热部署
    iOS bug处理
    iOS8-xcode6中添加pch全局引用文件
  • 原文地址:https://www.cnblogs.com/luomingui/p/2097174.html
Copyright © 2011-2022 走看看