将某个EXE设为开机启动项 .NET实现
1 private void btnSetOk_Click(object sender, EventArgs e) 2 3 { 4 5 RegCompStartRun(true, txtFullPath.Text.Trim()); 6 7 } 8 9 10 11 private void btnCancel_Click(object sender, EventArgs e) 12 13 { 14 15 RegCompStartRun(false, txtFullPath.Text.Trim()); 16 17 } 18 19 20 21 private void RegCompStartRun(bool cmd, string argPath) 22 23 { 24 25 lblDisplay.Text = ""; 26 27 28 29 string starupPath = argPath; 30 31 if (string.IsNullOrEmpty(argPath)) 32 33 { 34 35 //获取当前可执行程序的全路径 36 37 starupPath = Application.ExecutablePath; 38 39 } 40 41 42 43 //表示Window注册表中项级节点,读取 Windows 注册表基项HKEY_LOCAL_MACHINE 44 45 Microsoft.Win32.RegistryKey loca = Microsoft.Win32.Registry.LocalMachine; 46 47 Microsoft.Win32.RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); 48 49 try 50 51 { 52 53 //SetValue:存储值的名称 54 55 if (cmd) 56 57 { 58 59 if (run.GetValue("AutoStartupTestWinFormApp") == null) 60 61 { 62 63 run.SetValue("AutoStartupTestWinFormApp", starupPath);//加入注册,参数一为注册节点名称(随意) 64 65 lblDisplay.Text = "设置成功!"; 66 67 } 68 69 } 70 71 else 72 73 { 74 75 if (run.GetValue("AutoStartupTestWinFormApp") != null) 76 77 { 78 79 run.DeleteValue("AutoStartupTestWinFormApp", false);//删除该注册节点 80 81 lblDisplay.Text = "取消设置成功!"; 82 83 } 84 85 } 86 87 loca.Close(); 88 89 run.Close(); 90 91 } 92 93 catch (Exception ee) 94 95 { 96 97 MessageBox.Show(ee.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); 98 99 } 100 101 }
注意事项:
如果设置后,重命名该exe文件,则注销、重启后重新登录,设置的开机启动项不会启动,
如果改回原来的名字,则再次注销或重启,登录后会自动启动该设置的exe文件
版权声明:本文为MRRAOBX原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。