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

58

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

我该如何在生产环境中默认将我的应用程序运行在管理员模式下?

6个回答

91
您需要添加一个app.manifest文件。将requestedExecutionLevelasInvoker更改为requireAdministrator。您可以通过使用添加文件对话框创建新的清单,并将其更改为需要管理员权限。确保您的项目设置也设置为使用该清单。这将使您只需双击应用程序,如果尚未提升,则会自动提示进行提升。
有关更多文档,请参见此处: http://msdn.microsoft.com/en-us/library/bb756929.aspx 编辑: 值得一提的是,文章使用VS 2005并使用mt.exe嵌入清单。如果您使用Visual Studio 2008+,则内置了此功能。只需打开项目的属性,在“应用程序”选项卡上选择清单即可。

2
这个在Windows 7上能用吗?那一页有一个提出这个问题的注释... 在将来的版本中,唯一以提高权限运行应用程序的方式将是具有标识应用程序所需权限级别的已签名应用程序清单。 - Dean Kuga
如果我在Windows Server 2008机器上安装我的应用程序,这个方案可行吗?因为我在运行应用程序时遇到了问题。 - SVI
2
谢谢VCSJones,您的解决方案对我有用。我必须禁用ClickOnce才能消除那个错误。我通过进入项目属性,安全选项卡并取消选中“启用ClickOnce安全设置”选项来实现这一点。 - SVI
当我选择“查看UAC设置(app.manifest)”并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />更改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />时,我会收到一个错误提示:“错误6:ClickOnce不支持请求执行级别'requireAdministrator'。”根据MSDN的说法,这是准确的。 - Michael Eakins
这个能在VS2013 Express中使用吗?除了ClickOnce,我们好像没有其他的部署方式。 - dotNET
显示剩余5条评论

30
  1. 右键单击您的WPF项目,添加新项目:“添加->新项目…”
  2. 选择“应用程序清单文件”,然后单击“添加”
  3. 双击新创建的清单文件,更改
注意不要删除任何HTML标签。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />

为了

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

那么这个WPF应用程序将作为管理员运行。


工作正常。 :) - Naveen Kumar V

4

如果您不想损坏 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


那是唯一的解决方案,而不会破坏ClickOne标志和安全性。如果你想使用发布该解决方案。 - TAO

4

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

1.打开“解决方案资源管理器”

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

3.按以下方式编辑清单文件:

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

(TO)

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

4. 在编辑清单文件后,转到解决方案项目(右键单击)------>属性------->安全性

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

  1. 运行应用程序,并进行安装,现在已经实现以管理员身份运行应用程序。

如果第二步没有App.Manifest可供选择怎么办?我不知道我的项目出了什么问题,但是我在使用Visual Studio 2019和WPF C#时真的没有清单文件可供选择。 - Noryn Basaya
@NorynBasaya 对我而言,它存在并被称为“应用清单文件”。 - LiamJM

2

WPF App.xaml.cs
当前应用程序进程将被终止,然后以管理员身份启动相同的应用程序进程。

public partial class App : Application
{
        //This function will be called on startup of the applications
        protected override void OnStartup(StartupEventArgs e)
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false && principal.IsInRole(WindowsBuiltInRole.User) == true)
            {
                ProcessStartInfo objProcessInfo = new ProcessStartInfo();
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.FileName = Assembly.GetEntryAssembly().CodeBase;
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.Verb = "runas";
                try
                {
                    Process proc = Process.Start(objProcessInfo);
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                }
            }
        }
}

0

我发现这个代码可以帮助我以我想要的正确方式完成它。

我希望应用程序在“用户选择为管理员”的情况下运行,而不是让应用程序本身作为管理员运行。

这种方法强制用户以管理员身份运行应用程序

所以这就是我的最终代码

public partial class App : Application
{
    public static bool IsUserAdministrator()
    {
        try
        {
            WindowsIdentity user = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(user);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch
        {
            return false;
        }
    }

    protected override void OnStartup(StartupEventArgs e)
    {

        if (!IsUserAdministrator())
        {

            //TODO if NOT RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("not admin");
            Application.Current.Shutdown();
        }
        else
        {
            //TODO if RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("Admin");
        }

    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接