【问题标题】:Windows 7 and Vista UAC - Programmatically requesting elevation in C#Windows 7 和 Vista UAC - 在 C# 中以编程方式请求提升
【发布时间】:2011-01-17 22:54:53
【问题描述】:

我有一个程序只需要在极少数情况下提升为管理员,因此我不想将我的清单设置为需要永久提升。

如何仅在需要时以编程方式请求提升?

我正在使用 C#

【问题讨论】:

    标签: c# windows-7 windows-vista uac


    【解决方案1】:
    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;
    }
    

    【讨论】:

    • 这是正确的答案,但RunElevated 可能应该返回一个bool,这样您就可以在用户取消提升时进行投诉。
    • 另外,由于您将要关闭并重新启动应用程序,如果有要保存的状态,请注意这一点。您可能更愿意将需要提升的内容分区并启动提升而不关闭主应用程序。
    猜你喜欢
    • 2010-09-06
    • 2011-02-11
    • 1970-01-01
    • 2011-02-20
    • 2010-10-07
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多