在应用程序清单文件中设置 UIAccess

在应用程序清单文件中设置 UIAccess

若要获取对受保护系统 UI 的访问权限,必须使用清单文件中包含特殊属性的清单文件生成应用程序。 此 uiAccess 属性包含在 requestedExecutionLevel 标记中,如以下代码示例所示。

XML

<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 
    <security> 
        <requestedPrivileges> 
        <requestedExecutionLevel 
            level="highestAvailable" 
            uiAccess="true" /> 
        </requestedPrivileges> 
    </security> 
</trustInfo> 

此代码中 级别 特性的值只是一个示例。

默认情况下,UIAccess 为“false”。 如果省略该属性,或者没有清单,则应用程序无法访问受保护的 UI。

在C#程序请求管理员权限可以通过在app.manifest文件设置请求管理员权限,或者使用代码请求管理员权限。 方法一:在app.manifest文件设置请求管理员权限 在项目的app.manifest文件,找到下面的代码块,并将requestedExecutionLevel的level属性设置为requireAdministrator。 ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` 方法二:使用代码请求管理员权限 使用代码请求管理员权限需要使用Windows API函数,可以使用下面的代码: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace AdminLauncher { class Program { [DllImport("user32.dll", SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetConsoleWindow(); static void Main(string[] args) { if (!IsAdmin()) { StartAsAdmin(); return; } // 操作管理员权限下的资源 } static bool IsAdmin() { var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); var principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } static void StartAsAdmin() { var fileName = Process.GetCurrentProcess().MainModule.FileName; var startInfo = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = fileName, Verb = "runas" }; Process.Start(startInfo); ShowWindow(GetConsoleWindow(), 0); } } } ``` 以上代码,IsAdmin方法用于判断当前程序是否以管理员权限运行,如果是,则执行管理员权限下的操作,否则调用StartAsAdmin方法以管理员权限重新启动程序。StartAsAdmin方法使用ProcessStartInfo对象来设置启动参数,其Verb属性设置为"runas"表示以管理员权限启动程序。注意,使用Verb属性可能会弹出UAC提示框,需要用户授权才能继续执行,如果不想显示UAC提示框,可以使用Windows API函数ShowWindow将控制台窗口隐藏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值