如果想你写的程序随系统开机一起启动的话,那么你可以照下面这个方法来做。
RunWhenStart(false, Application.ProductName, Application.StartupPath + @\"\\MUS.exe\");
/// <summary> /// 开机启动项 /// </summary> /// <param name=\"Started\">是否启动</param> /// <param name=\"name\">启动值的名称</param> /// <param name=\"path\">启动程序的路径</param> public static void RunWhenStart(bool bStarted, string name, string path) { RegistryKey hklm = Registry.LocalMachine; RegistryKey run = hklm.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\"); try { if (bStarted) { run.SetValue(name, path); } else { run.DeleteValue(name); } } catch (Exception err) { MessageBox.Show(err.Message.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { hklm.Close(); run.Close(); } }
添加一个checkbox在启动时显示于用户界面,并添加CheckedChanged事件,即可以通过checkbox设置是否随时启动。
/// <summary> /// 设置开机自动启动 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void chrb_CheckedChanged(object sender, EventArgs e) { string startPath = Application.ExecutablePath; RunWhenStart(chrb.Checked, "SendMessage", startPath); }