App.xaml 中订阅事件 Startup += CheckAdministrator
/// <summary>
/// 检测是否以管理员身份运行
/// </summary>
private void CheckAdministrator()
{
var wi = System.Security.Principal.WindowsIdentity.GetCurrent();
var wp = new System.Security.Principal.WindowsPrincipal(wi);
bool runAsAdmin = wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
if (!runAsAdmin)
{
var processInfo = new ProcessStartInfo(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
try
{
Process.Start(processInfo);
}
catch (Exception ex)
{
MessageBox.Show("程序自动以管理员身份运行出错,请手动设置以管理员身份运行程序" + ex);
throw;
}
Environment.Exit(0);
}
}