如何强制WPF应用程序以管理员模式运行

时间:2011-03-11 18:08:48

标签: wpf admin mode

我有一个WPF应用程序,它访问本地机器上的Windows服务,任务调度程序。 当我部署此WPF应用程序并在没有“以管理员身份运行”的情况下运行它时,它会失败,因为它无法访问本地计算机上的Windows服务和任务计划程序。如果我使用“以管理员身份运行”运行它,它可以正常工作。

在生产中部署应用程序时,如何使我的应用程序默认以管理模式运行?

4 个答案:

答案 0 :(得分:73)

您需要添加app.manifest。更改requestedExecutionLevel  从asInvokerrequireAdministrator。您可以使用添加文件对话框创建新清单,将其更改为需要管理员。确保您的项目设置也设置为使用该清单。这将允许您只需双击应用程序,它将自动提示升级(如果尚未提升)。

有关更多文档,请参阅此处:

http://msdn.microsoft.com/en-us/library/bb756929.aspx

编辑: 对于它的价值,本文使用VS 2005并使用mt.exe嵌入清单。如果您使用的是Visual Studio 2008+,则内置它。只需打开项目的属性,然后在“应用程序”选项卡上选择清单。

答案 1 :(得分:2)

  1. 右键单击您的WPF项目以添加新项目:“添加->新项目...”
  2. 选择“应用程序清单文件”,然后单击“添加”
  3. 双击您新创建的清单文件,然后更改
    <requestedExecutionLevel level="asInvoker" uiAccess="false" />

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

然后WPF应用程序将以管理员身份运行。

答案 2 :(得分:2)

使WPF应用程序以管理员模式运行的步骤

1。打开解决方案资源管理器

2。右键单击解决方案--->添加---->新建项----> App.Manifest ---->确定

3。按如下所示编辑清单文件:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

(TO)

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

4。编辑清单文件后,转到解决方案项目(RightCLick)------>属性------->安全性

关闭“启用ClickOnce安全设置”复选框

  1. 运行该应用程序,并进行设置,现在可以实现“以管理员身份运行”模式的应用程序。

答案 3 :(得分:0)

如果您不想破坏Clickonce,则此代码是最佳解决方案:

using System.Security.Principal;
using System.Management;
using System.Diagnostics;
using System.Reflection;
//Put this code in the main entry point for the application
// Check if user is NOT admin 
if (!IsRunningAsAdministrator())
{
    // Setting up start info of the new process of the same application
    ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase);

    // Using operating shell and setting the ProcessStartInfo.Verb to “runas” will let it run as admin
    processStartInfo.UseShellExecute = true;
    processStartInfo.Verb = "runas";

    // Start the application as new process
    Process.Start(processStartInfo);

    // Shut down the current (old) process
    System.Windows.Forms.Application.Exit();
    }
}

/// <summary>
/// Function that check's if current user is in Aministrator role
/// </summary>
/// <returns></returns>
public static bool IsRunningAsAdministrator()
{
    // Get current Windows user
    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

    // Get current Windows user principal
    WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

    // Return TRUE if user is in role "Administrator"
    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

成立于:http://matijabozicevic.com/blog/wpf-winforms-development/running-a-clickonce-application-as-administrator-also-for-windows-8