【发布时间】:2011-01-17 22:54:53
【问题描述】:
我有一个程序只需要在极少数情况下提升为管理员,因此我不想将我的清单设置为需要永久提升。
如何仅在需要时以编程方式请求提升?
我正在使用 C#
【问题讨论】:
标签: c# windows-7 windows-vista uac
我有一个程序只需要在极少数情况下提升为管理员,因此我不想将我的清单设置为需要永久提升。
如何仅在需要时以编程方式请求提升?
我正在使用 C#
【问题讨论】:
标签: c# windows-7 windows-vista uac
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,这样您就可以在用户取消提升时进行投诉。