最近在做一个自动备份文件的小工具,需要用到开机自启动
下面是代码
private void checkBox8_CheckedChanged(object sender, EventArgs e)
{
try
{
//设置开机自启动
if (checkBox8.Checked == true)
{
/*方法一*/
string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
//获得文件的当前路径
string dir = Directory.GetCurrentDirectory();
//获取可执行文件的全部路径
string exeDir = dir + @"\自动备份.exe.lnk";
File.Copy(exeDir, StartupPath + @"\自动备份.exe.lnk", true);
/*方法二*/
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue("JcShutdown", path);
rk2.Close();
rk.Close(); }
//取消开机自启动
else
{
/*方法一*/
string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
System.IO.File.Delete(StartupPath + @"\EcgNetPlug.exe.lnk");
/*方法二*/
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.DeleteValue("JcShutdown", false);
rk2.Close();
rk.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
第一种方法原理是直接把可执行文件的快捷方式复制到系统的启动目录里,这种方式不会被安全软件拦截,不需要额外的权限
第二种方式是直接写注册表,这种方式可能会把安全软件拦截
大家可以自己试试,有问题可以留言,我也是边学边做
作者:逐梦
出处:http://www.cnblogs.com/huanjun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利