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

5
我有一个在Visual Studio 2013中的WPF项目,这个项目有两个按钮。第一个按钮说“启动服务”,第二个说“停止服务”。 当我以管理员身份运行我的Visual Studio时,按钮可以正常工作。但是当我没有特权打开我的Visual Studio时,就会出现InvalidOperationException异常。
如何强制使我的项目在Visual Studio不以管理员身份运行时具有特权?
我向我的项目添加了app.manifest并将其更改为 level="requireAdministrator" uiAccess="false"/>
但它没有起作用。
为了启动或停止我的服务,我正在使用ServiceController。

这个解决方案对我来说没有起作用。 - CampDev
您的评论没有解决您的问题。 - Hans Passant
WPF应用程序使用WCFService中的方法来停止或启动服务...这会有一些影响吗? - CampDev
你想以管理员身份调试吗? - RadioSpace
我希望我的项目始终具有特权,尽管 Visual Studio 不会以特权启动。 - CampDev
2个回答

8

正如Torben M. Philippsen在他的文章中所提到的:

  • In Visual Studio 2010 (I guess the same applies to VS2008, but I haven’t tested it) right click Your project and select “add new item”
  • Add a application manifest file – the default name will be app.manifest.
  • Inside the manifest file, change the existing configuration from

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

    To

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    
  • Save and close the manifest file.

  • Please note that Your manifest file won’t show up anywhere in your solution. In order to fix that, in solution explorer, click the “show all files” button.
  • Important: Right click the manifest file and add it to the project – we need that in order to tell VS to use the manifest file when compiling our application.
  • Right click Your project and select “properties”.
  • On the application tab, the bottom section, select the manifest file:

Selecting manifest file

清单文件选择
  • Compile and run the application. If Your UAC settings are enabled, You will be prompted to allow the application to start in elevated mode.

  • Sometimes it can come in handy to check whether Your application is actually running in elevated mode or not. Maybe You will find this codesnippet usefull:

     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安全性


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