public static void StartRun()
{
string strName = Application.ExecutablePath;
string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);
if (!File.Exists(strName))//指定文件是否存在
return;
try
{
Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (Rkey == null)
{
Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
Rkey.SetValue(strnewName, strName);//修改注册表,使程序开机时自动执行。
}
else
{
//Rkey.DeleteValue(strnewName);//删除注册表。
Rkey.SetValue(strnewName, strName);//修改注册表,使程序开机时自动执行。
}
}
catch (Exception ex)
{
new AggregateException("StartRun", ex); //MessageBox.Show(ex.Message);
}
}
在程序运行的时候,执行这个方法就行了。
亲测可用,但是有个要注意的地方,就是有时不起作用,那就先删掉注册表中SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run的所有内容就行了