1. 用WPF开发,需要管理员权限并开机启动,以写注册表的方式实现。仅写注册表只能启动一般权限的程序。
2. 考虑这样实现: 程序以一般权限启动,启动以后申请管理员权限。
实现:
App类中重写OnStartup事件,判断当前程序的权限,如果不是管理员权限,则申请权限,重启进程并关闭当前进程:
WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { if (IsRunningOne(fileName)) { MessageBox.Show("already exit"); Application.Current.Shutdown(); Environment.Exit(0); } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = Assembly.GetExecutingAssembly().Location; startInfo.Verb = "runas"; Process.Start(startInfo); Current.Shutdown(); Environment.Exit(0); }
如果已经有实例运行,则不启动。
3. 开机启动的程序,获取当前exe所在路径的值为“C:WindowsSystem32”
App类:,其中不允许运行两个实例。
public partial class App : Application { string fileName = "SystemManager"; private bool IsRunning(string fileName) { return Process.GetProcessesByName(fileName).Length > 2; } private bool IsRunningOne(string fileName) { return Process.GetProcessesByName(fileName).Length > 1; } protected override void OnStartup(StartupEventArgs e) { if (Debugger.IsAttached) { base.OnStartup(e); return; } if (!IsRunning(fileName)) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { if (IsRunningOne(fileName)) { MessageBox.Show("already exit"); Application.Current.Shutdown(); Environment.Exit(0); } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = Assembly.GetExecutingAssembly().Location; startInfo.Verb = "runas"; Process.Start(startInfo); Current.Shutdown(); Environment.Exit(0); } } else { MessageBox.Show("实例运行超过2个"); } //base.OnStartup(e); } }