添加启动项
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if(key == null)//如果该项不存在的话,则创建该子项 { key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); } key.SetValue("RandomQuotation", Assembly.GetExecutingAssembly().Location); key.Close();
其中Assembly.GetExecutingAssembly().Location是获取当前程序的路径,使用了反射技术所以在一开头还需要添加
using System.Reflection;
删除启动项
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项 if(key != null) { try { key.DeleteValue("RandomQuotation"); } catch(Exception) { return; } }
如果删除值不存在,或者是只读的,会抛出异常.
另外可以使用以下代码监测一值是否存在
object obj= Registry.GetValue("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", "RandomQuotation",null); if(obj==null) { MessageBox.Show("键不存在"); }