标签:分享 uri process ide 以管理员身份运行 als set system wpf
针对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); } }
标签:分享 uri process ide 以管理员身份运行 als set system wpf
原文地址:http://www.cnblogs.com/machenghu/p/6424589.html