在使用C#进行应用程序的开发过程中,经常有一个需求就是让应用程序开机后自动启动,这个是一个很常见的需求,最常规的做法(这里以Win7操作系统为例),打开:开始=》所有程序=》启动文件夹(路径是:C:\Users\bobo\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup),然后可以将exe(这里以X.Shell.exe为例来说明)或者其快捷方式放到当前文件夹下面,这样我们就可以在应用程序下次启动的时候自动启动当前应用程序中,同时我们也可以通过:Windows+R然后输入msconfig来查看系统配置,在启动中来查看启动项目,我们会看到在启动项下面会有刚才添加的应用程序X.Shell.exe,如下图所示:

这是我们再通过:Windows+R==>regedit来查看注册表信息,开是否写入了注册表中:我们没有发现写入到Windows的注册表中,注:Windows的默认开机启动项是写到:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run这个键值下面。

所以最为合理的方式就是将exe程序写入到注册表中,首先看看插入和删除注册表信息的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | private void AutoRunAfterStart() { //获取当前应用程序的路径 string localPath = Application.ExecutablePath; if (!System.IO.File.Exists(localPath)) //判断指定文件是否存在 return ; RegistryKey reg = Registry.LocalMachine; RegistryKey run = reg.CreateSubKey( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run" ); //判断注册表中是否存在当前名称和值 if (run.GetValue( "ControlPanasonic.exe" ) == null ) { try { run.SetValue( "ControlPanasonic.exe" , localPath); MessageBox.Show( " 当前应用程序已成功写入注册表!" , "温馨提示" , MessageBoxButtons.OK, MessageBoxIcon.Information); reg.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "温馨提示" , MessageBoxButtons.OK, MessageBoxIcon.Error); } } } //删除注册表钟的特定值 private void DeleteSubKey() { RegistryKey reg = Registry.LocalMachine; RegistryKey run = reg.OpenSubKey( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run" , true ); try { run.DeleteValue( "ControlPanasonic.exe" ); MessageBox.Show( " 当前应用程序已成功从注册表中删除!" , "温馨提示" , MessageBoxButtons.OK, MessageBoxIcon.Information); reg.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "温馨提示" ,MessageBoxButtons.OK, MessageBoxIcon.Error); } } |
现在就上面的代码做一些简要的分析,RegistryKey reg = Registry.LocalMachine;RegistryKey run = reg.CreateSubKey(@"SOFTWARE\Microsoft \Windows \CurrentVersion\Run");这两句代码的核心是获取RegistryKey 的对象,然后通过SetValue以及DeleteValue将当前的exe写入到注册表中,这样就能够永久去保存当前的键值对,从而确定开机启动项。
原文地址:https://www.cnblogs.com/seekdream/p/5815926.html