C#启动项

来源:互联网 发布:淘宝3d虚拟试穿衣服 编辑:程序博客网 时间:2024/06/13 01:26
添加添加启动项
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("键不存在");
}
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("键不存在");
}
0 0