Windows 7和Vista UAC - 在C#中以编程方式请求提升

26

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

当我需要时如何通过编程请求提升?

我正在使用C#。

1个回答

30
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = principal.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;
}

4
这是正确的答案,但是RunElevated应该返回一个bool,这样如果用户取消了提权操作,你就能够进行相应处理。 - user203570
3
由于您将要关闭并重新启动应用程序,如果需要保存状态,请处理好。您可能更喜欢将需要提升权限的内容分区,并在不关闭主应用程序的情况下启动该提升权限的内容。 - Kate Gregory
1
在2022年的Win10上运行时,我发现我必须添加processInfo.UseShellExecute = true才能获取UAC窗口。(除此之外,没有任何抱怨!) - Petter Hesselberg

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