1:获取当前用户:
cs
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
2:判断当前用户是否是管理员如果是则直接启动否则通过Process启动:
(如果不这样处理直接使用非admin权限对注册表进行编辑操作程序将报异常)
cs
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员则直接启动
Application.Run(new Form1());
}
else
{
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
//启动的应用程序
startinfo.FileName = Application.ExecutablePath;
//设置启动动作,以管理员身份启动
startinfo.Verb = "runas";
var process= System.Diagnostics.Process.Start(startinfo);
Application.Exit();
}
3:对注册表进行编辑,设置启动路径
cs
RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);
//当前启动的项目
//string app = Application.ExecutablePath;
//获取的路径格式为:D:\Program Files (x86)/360/360Safe/safemon/360tray.exe
//该格式无法达到开机启动的目的。
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
//格式:D:\Program Files (x86)\360\360Safe\safemon\360tray.exe
//该格式实现开机启动
Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN").SetValue("MyAngel", app, RegistryValueKind.String); //打开注册表中的现有项并设置其中的键值类型
4:注销开机自启动功能(可选):
cs
//删除该启动项
RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree);
runKey.DeleteValue("MyAngel");
runKey.Close();
5:特别注意事项:
1,虽然使用:
cs
Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN").SetValue("MyAngel", app, RegistryValueKind.String);
理论上添加的键值信息应该是存储在:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
实际上有可能存储在:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
2,设置的值其格式必须注意:
SetValue("MyAngel", app, RegistryValueKind.String);
app存储的字符串格式只能是 :D:\Program Files (x86)\360\360Safe\safemon\360tray.exe
而不能是:D:\Program Files (x86)/360/360Safe/safemon/360tray.exe
如果格式异常则无法达到开机自启动的目的。