ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

C#设置程序开机启动

2026/8/12 22:34:17 拓冰建站 浏览量
C#设置程序开机启动

1:获取当前用户:

 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);

2:判断当前用户是否是管理员如果是则直接启动否则通过Process启动:

(如果不这样处理直接使用非admin权限对注册表进行编辑操作程序将报异常)

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:对注册表进行编辑,设置启动路径

 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:注销开机自启动功能(可选):

 //删除该启动项RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree);runKey.DeleteValue("MyAngel");runKey.Close();

5:特别注意事项:

 1,虽然使用:

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

如果格式异常则无法达到开机自启动的目的。