您的位置:首页 > 编程语言 > C#

C#使用注册表添加删除开机启动项

2012-06-20 11:50 330 查看

添加启动项

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("键不存在");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: