win7桌面,如何让 Win7 下的桌面应用程序以管理员权限运行

Vista 和 Windows 7 操作系统为了加强安全,增加了 UAC(用户账户控制) 的机制,如果 UAC 被打开,用户即使是以管理员权限登录,其应用程序默认情况下也无法对系统目录,系统注册表等可能影响系统运行的设置进行写操作。这个机制大大增强了系统的安全性,但对应用程序开发者来说,我们不能强迫用户去关闭UAC,但有时我们开发的应用程序又需要以 Administrator 的方式运行,即 Win7 中 以 as administrator 方式运行,那么我们怎么来实现这样的功能呢?
我们在 win7 下运行一些安装程序时,会发现首先弹出一个对话框,让用户确认是否同意允许这个程序改变你的计算机配置,但我们编写的应用程序默认是不会弹出这个提示的,也无法以管理员权限运行。本文介绍了 C# 程序如何设置来提示用户以管理员权限运行。
首先在项目中增加一个 Application Manifest File
imagewin7桌面,如何让 Win7 下的桌面应用程序以管理员权限运行
默认的配置如下:
xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

我们可以看到这个配置中有一个 requestedExecutionLevel 项,这个项用于配置当前应用请求的执行权限级别。这个项有3个值可供选择,如下表所示:
Value Description Comment
asInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
highestAvailable The application runs with the highest privileges the current user can obtain. Recommended for mixed-mode applications. Plan to refractor the application in a future release.
requireAdministrator The application runs _disibledevent=>Recommended for administrator _disibledevent=>Create and Embed an Application Manifest (UAC)
下面是修改后的配置文件:
xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

配置文件修改后,我们运行应用程序,就会首先弹出这样一个提示框,点 Yes 后,程序才可以继续运行,并且获得系统管理员的权限。
imageimagewin7桌面,如何让 Win7 下的桌面应用程序以管理员权限运行
Tags:  win7桌面

延伸阅读

最新评论

发表评论