Windows 7和Vista UAC - 在C#编程方式请求海拔 [英] Windows 7 and Vista UAC - Programatically requesting elevation in C#

查看:143
本文介绍了Windows 7和Vista UAC - 在C#编程方式请求海拔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,只需要提升到admin于极少数情况下,所以我不希望建立我的清单,要求永久提升。

如何通过编程要求海拔只有当我需要它?

我使用C#
谢谢


解决方案

  WindowsPrincipal pricipal =新的WindowsPrincipal(WindowsIdentity.GetCurrent());
布尔hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);如果(!hasAdministrativeRight)
{
    RunElevated(Application.ExecutablePath);
    this.Close();
    Application.Exit();
}私人静态布尔RunElevated(字符串文件名)
{
    //MessageBox.Show(\"Run:+文件名);
    的ProcessStartInfo processInfo =新的ProcessStartInfo();
    processInfo.Verb =运行方式;
    processInfo.FileName =文件名;
    尝试
    {
        的Process.Start(processInfo);
        返回true;
    }
    赶上(Win32Exception)
    {
        //没做什么。也许用户取消了UAC窗口
    }
    返回false;
}

I have a program that only requires elevation to Admin on very rare occasions so I do not want to set-up my manifest to require permanent elevation.

How can I Programatically request elevation only when I need it?

I am using C# Thanks

解决方案

WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

if (!hasAdministrativeRight)
{
    RunElevated(Application.ExecutablePath);
    this.Close();
    Application.Exit();
}

private static bool RunElevated(string fileName)
{
    //MessageBox.Show("Run: " + fileName);
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.Verb = "runas";
    processInfo.FileName = fileName;
    try
    {
        Process.Start(processInfo);
        return true;
    }
    catch (Win32Exception)
    {
        //Do nothing. Probably the user canceled the UAC window
    }
    return false;
}

这篇关于Windows 7和Vista UAC - 在C#编程方式请求海拔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆