首页 > 编程 > C# > 正文

.NET实现:将EXE设置开机自动启动

2020-01-24 03:34:11
字体:
来源:转载
供稿:网友

复制代码 代码如下:

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)

      {

          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)

              {

                  run.SetValue("AutoStartupTestWinFormApp", starupPath);//加入注册,参数一为注册节点名称(随意)  

                  lblDisplay.Text = "设置成功!";

              }

              else

              {

                  run.DeleteValue("AutoStartupTestWinFormApp", false);//删除该注册节点    

                  lblDisplay.Text = "取消设置成功!";

              }

              loca.Close();

          }

          catch (Exception ee)

          {

              MessageBox.Show(ee.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

          }

      }

注意事项:

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表