【问题标题】:How to force my project in Visual Studio 2013 to always run as Administrator?如何强制我在 Visual Studio 2013 中的项目始终以管理员身份运行?
【发布时间】:2014-05-12 21:59:19
【问题描述】:

我在 Visual Studio 2013 中有一个 WPF 项目,该项目有两个按钮。第一个按钮说启动服务,第二个说停止服务。 当我以管理员身份运行 Visual Studio 时,这些按钮起作用。但是,当我打开没有权限的 Visual Studio 时,会出现 InvalidOperationException 异常。

当 Visual Studio 不以管理员身份运行时,如何强制我的项目以特权启动?

我将 app.manifest 添加到我的项目并更改为

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

但它不起作用。

为了启动或停止我的服务,我使用的是 ServiceController。

【问题讨论】:

标签: c# wpf service visual-studio-2013 elevated-privileges


【解决方案1】:

正如 Torben M. Philippsen 在他的 article 中提到的那样:

  • 在 Visual Studio 2010 中(我想这同样适用于 VS2008,但我 尚未测试)右键单击您的项目并选择“添加新项目”
  • 添加应用程序清单文件 - 默认名称为 app.manifest。
  • 在清单文件中,更改现有配置

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

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    
  • 保存并关闭清单文件。

  • 请注意,您的清单文件不会出现在您的解决方案中的任何位置。要解决此问题,请在解决方案资源管理器中点击“显示所有文件”按钮。
  • 重要提示:右键单击清单文件并将其添加到项目中——我们需要它来告诉 VS 在编译我们的应用程序时使用清单文件。
  • 右键单击您的项目并选择“属性”。
  • 在应用程序选项卡的底部,选择清单文件:

清单文件选择

  • 编译并运行应用程序。如果您的 UAC 设置已启用,系统将提示您允许应用程序以提升模式启动。

  • 有时它可以派上用场,以检查您的应用程序是否实际上在提升模式下运行。也许你会发现这个coden-p很有用:

     WindowsPrincipal myPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
     if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) == false )
     {
         //show messagebox - displaying a messange to the user that rights are missing
         MessageBox.Show("You need to run the application using the \"run as administrator\" option", "administrator right required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     }
     else
     {
         MessageBox.Show("You are good to go - application running in elevated mode", "Good job" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
    

【讨论】:

    【解决方案2】:

    这很有趣,您似乎需要更改项目运行方式的权限,请尝试执行以下操作

    • 转到项目属性>安全性
    • 启用单击一次安全设置并选择完全信任应用程序

    此链接中的更多信息 WPF security

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2011-05-07
      相关资源
      最近更新 更多