开机启动
using System; using System.Windows.Forms; using Microsoft.Win32; namespace RegistryUtil { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SetAutoBootStatu(true); } /// <summary> /// 在注册表中添加、删除开机自启动键值 /// </summary> public static int SetAutoBootStatu(bool isAutoBoot) { try { string execPath = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"); if (isAutoBoot) { rk2.SetValue("MyExec", execPath); Console.WriteLine(string.Format("[注册表操作]添加注册表键值:path = {0}, key = {1}, value = {2} 成功", rk2.Name, "TuniuAutoboot", execPath)); } else { rk2.DeleteValue("MyExec", false); Console.WriteLine(string.Format("[注册表操作]删除注册表键值:path = {0}, key = {1} 成功", rk2.Name, "TuniuAutoboot")); } rk2.Close(); rk.Close(); return 0; } catch (Exception ex) { Console.WriteLine(string.Format("[注册表操作]向注册表写开机启动信息失败, Exception: {0}", ex.Message)); return -1; } } } }
需要注意的是:
Windows中微软的注册表信息是分32位和64位的:
32位:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft
64位:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft
以下代码
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
rk2.SetValue("MyExec", execPath);
在32位机器上执行,那么没有问题,变量会创建在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run下。但是如果在64位机器上执行,会自动创建在
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) //设置开机自启动 { MessageBox.Show ("设置开机自启动,需要修改注册表","提示"); 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 //取消开机自启动 { MessageBox.Show ("取消开机自启动,需要修改注册表","提示"); 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(); } }