c# 代码 添加或删除程序开机启动

  1. /向注册表添加开机起动  
  2.         private void button1_Click(object sender, System.EventArgs e) //button1按下后,会执行的方法   
  3.         {  
  4.             RegistryKey hklm = Registry.LocalMachine;//需要引用 Microsoft.Win32  
  5.   
  6.             //定义hklm指向注册表的LocalMachine,对注册表的结构,可以在windows的运行里,输入regedit,运行后,可以看看里面的各个子键,  
  7.             //其中Software/Microsoft/Windows/CurrentVersion/Run就是关系到系统中随系统启动而启动的程序,通称启动项   
  8.   
  9.               
  10.             RegistryKey run = hklm.CreateSubKey(@"Software/Microsoft/Windows/CurrentVersion/Run");   
  11.             try  
  12.             {  
  13.                 //将我们的程序加进去,系统启动时,hello.exe就会随系统启动而启动了,后面F:/C#....就这个程序的位置,你可以将hello.exe   
  14.                 //换成你自己的,比如:notepad.exe注意修改这个程序的位置。至于"@"这个符号加在"F:/C#/hello/"之前的作用,是为了保证.net编译器,  
  15.                 //不将/解释为转换符,如果这里不用@的话,那就应该写成"F://C#//hello//",一个/就要改为两个//。   
  16.                 //run.SetValue("hello.exe", @"F:/c#/hello/bin/Debug/hello.exe");  
  17.   
  18.                 //Application.StartupPath ------------ Get the folder Path of Currently  
  19.                 //Application.ExecutablePath ------------ Get the file Path of Currently  
  20.                 run.SetValue("MyNote.exe", @"" + Application.ExecutablePath);  
  21.   
  22.                 //弹出信息框,提示,已经成功添加了。要了解MessageBox.Show的各参数意义,可以将光标放到其里面,按F1,.net的IDE(集成开发环境)  
  23.                 //会有详细的文档显示出来,告诉您最权威详尽的解释。   
  24.                 MessageBox.Show("添加注册表启动项成功!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  25.                 hklm.Close();  
  26.             } //注意,一定要关闭,注册表应用。   
  27.             catch (Exception my) //这是捕获异常的   
  28.             {  
  29.                 MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  30.             }  
  31.   
  32.         }  
  33.   
  34.         //删除注册表内的开机起动  
  35.         private void button2_Click(object sender, System.EventArgs e) //button1是添加,这个button2是删除。后面的实现都差不多   
  36.         {  
  37.             RegistryKey hklm = Registry.LocalMachine;  
  38.             RegistryKey run = hklm.CreateSubKey(@"Software/Microsoft/Windows/CurrentVersion/Run");  
  39.             try  
  40.             {  
  41.                 //run.DeleteValue("hello.exe"); //这儿是关键的区别,删除hello.exe这个启动项键值   
  42.                 run.DeleteValue("MyNote.exe");  
  43.                 MessageBox.Show("移除注册表启动项成功!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  44.                 hklm.Close();  
  45.             }  
  46.             catch (Exception my)  
  47.             {  
  48.                 MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  49.             }  
  50.         }  

posted @ 2010-10-15 15:17  deepwishly  阅读(397)  评论(0编辑  收藏  举报