c# - 如何强制我在 Visual Studio 2013 中的项目始终以管理员身份运行?

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

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

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

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

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

但它没有起作用。

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

最佳答案

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

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

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

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

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

Selecting manifest file

list 文件选择

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

  • 有时它可以派上用场来检查您的应用程序是否确实在提升模式下运行。也许你会发现这个代码片段很有用:

     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);
     }
    

关于c# - 如何强制我在 Visual Studio 2013 中的项目始终以管理员身份运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797559/

相关文章:

c# - 如果不直接在窗口中居中,图像就会消失 [Margin not "0"]

android - 如何着手制作 Android MP3 播放器?

c# - 这个重构是什么模式?

c# - AutoResetEvent 与 bool 值停止线程

c# - 创建一个从阻塞线程订阅事件的表单

windows - 是否有一种编程方式来检测进程是否可以与桌面交互

delphi - Delphi 2009 可以构建返回数据集的 Web 服务吗?

c# - 如何绑定(bind)到 wpf 中的公共(public)类函数

wpf - 当出现验证错误时,防止失去 TextBox 焦点的最佳方法是什么?

.net - System.Reactive 5.0 中缺少 DispatcherScheduler