• 实现管理员身份运行软件


    针对WPF软件启动使用代码控制以管理员身份运行:

    1、app.manifest配置文件

    修改UAC 清单选项中requestedExecutionLevel 节点,将会禁用文件和注册表虚拟化。 

    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
          <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> 

            <!--<requestedExecutionLevel level="asInvoker" uiAccess="false" />
          <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
          <requestedExecutionLevel level="highestAvailable" uiAccess="false" />-->

            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
          </requestedPrivileges>
          <applicationRequestMinimum>
            <defaultAssemblyRequest permissionSetReference="Custom" />
            <PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true" />
          </applicationRequestMinimum>
        </security>
      </trustInfo>

    2、c#代码控制

    此处c#代码转载与http://blog.csdn.net/cleopard/article/details/40583595。重写OnStartup方法。

    protected override void OnStartup(StartupEventArgs e)  
          {  
              base.OnStartup(e);  
      
              CheckAdministrator();  
              //如果不是管理员,程序会直接退出,并使用管理员身份重新运行。  
              StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);  
          } 
     private void CheckAdministrator()
            {
                var wi = WindowsIdentity.GetCurrent();
                var wp = new WindowsPrincipal(wi);
    
                bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
    
                if (!runAsAdmin)
                {
                    // It is not possible to launch a ClickOnce app as administrator directly,
                    // so instead we launch the app as administrator in a new process.
                    var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);
    
                    // The following properties run the new process as administrator
                    processInfo.UseShellExecute = true;
                    processInfo.Verb = "runas";
    
                    // Start the new process
                    try
                    {
                        Process.Start(processInfo);
                    }
                    catch (Exception ex)
                    {
                        //ex.WriteLog();
                    }
    
                    // Shut down the current process
                    Environment.Exit(0);
                }
            }
  • 相关阅读:
    二分图 洛谷P2055 [ZJOI2009]假期的宿舍
    并查集 洛谷P1640 [SCOI2010]连续攻击游戏
    贪心 洛谷P2870 Best Cow Line, Gold
    贪心 NOIP2013 积木大赛
    快速幂 NOIP2013 转圈游戏
    倍增LCA NOIP2013 货车运输
    树形DP 洛谷P2014 选课
    KMP UVA1328 Period
    动态规划入门 BZOJ 1270 雷涛的小猫
    KMP POJ 2752Seek the Name, Seek the Fame
  • 原文地址:https://www.cnblogs.com/machenghu/p/6424589.html
Copyright © 2020-2023  润新知