using Microsoft.Win32; //操作注册表要用的名称空间
private void button1_Click(object sender, System.EventArgs e) //button1按下后,会执行的方法 { RegistryKey hklm=Registry.LocalMachine; RegistryKey run=hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); //定义hklm指向注册表的LocalMachine,对注册表的结构,可以在windows的运行里,输入regedit,运行后,可以看看里面的各个子键,其中Software\Microsoft\Windows\CurrentVersion\Run就是关系到系统中随系统启动而启动的程序,通称启动项 try { run.SetValue("hello.exe",@"F:\c#\hello\bin\Debug\hello.exe"); //将我们的程序加进去,系统启动时,hello.exe就会随系统启动而启动了,后面F:\C#....就这个程序的位置,你可以将hello.exe 换成你自己的,比如:notepad.exe注意修改这个程序的位置。至于"@"这个符号加在"F:\C#\hello\"之前的作用,是为了保证.net编译器,不将\解释为转换符,如果这里不用@的话,那就应该写成"F:\\C#\\hello\\",一个\就要改为两个\\。 MessageBox.Show("添加注册表启动项成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); //弹出信息框,提示,已经成功添加了。要了解MessageBox.Show的各参数意义,可以将光标放到其里面,按F1,.net的IDE(集成开发环境)会有详细的文档显示出来,告诉您最权威详尽的解释。 hklm.Close();} //注意,一定要关闭,注册表应用。 catch(Exception my) //这是捕获异常的 { MessageBox.Show(my.Message.ToString(),"提示",MessageBoxButtons.OK,MessageBoxIcon.Error); }
}
private void button2_Click(object sender, System.EventArgs e) //button1是添加,这个button2是删除。后面的实现都差不多 { RegistryKey hklm=Registry.LocalMachine; RegistryKey run=hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); try { run.DeleteValue("hello.exe"); //这儿是关键的区别,删除hello.exe这个启动项键值 MessageBox.Show("移除注册表启动项成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); hklm.Close(); } catch(Exception my) { MessageBox.Show(my.Message.ToString(),"提示",MessageBoxButtons.OK,MessageBoxIcon.Error); } }
|