wpf 以管理员运行1
代码形式
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Threading;
using System.Windows;
using SchoolClient.Utils;
using SchoolClient.Wins;
namespace SchoolClient
{
public partial class MyApp : Application
{
[STAThread]
private static void Main()
{
new MyApp();
}
public MyApp()
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
Run(new LoginWindow());
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Assembly.GetExecutingAssembly().Location;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
//退出
Application.Current.Shutdown();
}
}
}
}
判断程序是否以管理员运行
using System.Security.Principal;
public bool IsAdministrator()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
开机自启动写入注册表
#region 开机自启动写入注册表
private void RunAtStart()
{
var starupPath = GetType().Assembly.Location;
try
{
var fileName = starupPath;
var shortFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
//打开子键节点
var myReg = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.FullControl);
if (myReg == null)
{
//如果子键节点不存在,则创建之
myReg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
if (myReg != null && myReg.GetValue(shortFileName) != null)
{
//在注册表中设置自启动程序
myReg.DeleteValue(shortFileName);
myReg.SetValue(shortFileName, fileName);
LogHelper.WriteLog(typeof(MainWindow), "设置自启动程序操作成功");
}
else if (myReg != null && myReg.GetValue(shortFileName) == null)
{
myReg.SetValue(shortFileName, fileName);
LogHelper.WriteLog(typeof(MainWindow), "设置自启动程序操作成功");
}
}
catch
{
LogHelper.WriteLog(typeof(MainWindow),"写注册表操作发生错误");
}
}
#endregion