将某个EXE设为开机启动项 .NET实现

private void btnSetOk_Click(object sender, EventArgs e)
     {
         RegCompStartRun(true, txtFullPath.Text.Trim());
     }
 
     private void btnCancel_Click(object sender, EventArgs e)
     {
         RegCompStartRun(false, txtFullPath.Text.Trim());
     }
 
     private void RegCompStartRun(bool cmd, string argPath)
     {
         lblDisplay.Text = "";
 
         string starupPath = argPath;
         if (string.IsNullOrEmpty(argPath))
         {
             //获取当前可执行程序的全路径
             starupPath = Application.ExecutablePath;
         }
 
         //表示Window注册表中项级节点,读取 Windows 注册表基项HKEY_LOCAL_MACHINE 
         Microsoft.Win32.RegistryKey loca = Microsoft.Win32.Registry.LocalMachine;
         Microsoft.Win32.RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
         try
         {
             //SetValue:存储值的名称
             if (cmd)
             {
                 if (run.GetValue("AutoStartupTestWinFormApp") == null)
                 {
                     run.SetValue("AutoStartupTestWinFormApp", starupPath);//加入注册,参数一为注册节点名称(随意)   
                     lblDisplay.Text = "设置成功!";
                 }
             }
             else
             {
                 if (run.GetValue("AutoStartupTestWinFormApp") != null)
                 {
                     run.DeleteValue("AutoStartupTestWinFormApp", false);//删除该注册节点     
                     lblDisplay.Text = "取消设置成功!";
                 }
             }
             loca.Close();
             //run.Close();//注意此句是还原修改,请屏蔽掉..
         }
         catch (Exception ee)
         {
             MessageBox.Show(ee.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }

image

运行里面输入:
msconfig 表示查看开机启动项,引导区,启动服务等
regedit    表示查看注册表信息

注意事项:

如果设置后,重命名该exe文件,则注销、重启后重新登录,设置的开机启动项不会启动,

如果改回原来的名字,则再次注销或重启,登录后会自动启动该设置的exe文件

原文地址:https://www.cnblogs.com/jx270/p/2947175.html