首页 > 代码库 > 实现管理员身份运行软件
实现管理员身份运行软件
针对WPF软件启动使用代码控制以管理员身份运行:
1、app.manifest配置文件
修改UAC 清单选项中requestedExecutionLevel 节点,将会禁用文件和注册表虚拟化。
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!--<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> <applicationRequestMinimum> <defaultAssemblyRequest permissionSetReference="Custom" /> <PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true" /> </applicationRequestMinimum> </security> </trustInfo>
2、c#代码控制
此处c#代码转载与http://blog.csdn.net/cleopard/article/details/40583595。重写OnStartup方法。
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
CheckAdministrator();
//如果不是管理员,程序会直接退出,并使用管理员身份重新运行。
StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);
}
private void CheckAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { // It is not possible to launch a ClickOnce app as administrator directly, // so instead we launch the app as administrator in a new process. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator processInfo.UseShellExecute = true; processInfo.Verb = "runas"; // Start the new process try { Process.Start(processInfo); } catch (Exception ex) { //ex.WriteLog(); } // Shut down the current process Environment.Exit(0); } }
实现管理员身份运行软件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。