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:\ Windows \ System32”
应用程序类:不允许两个实例运行。
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); } }
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-376670-1.html
舍己为人的精神值得全世界学习
这是一个好演员