Winform 程序 开机启动

 设置程序的开机启动其实也就是在注册表中添加程序为开机启动项目,所以需要为程序指定一个唯一的注册表项Key 以及该程序执行文件所在的路径

       相关代码,如下:

 /// <summary>
/// 保存配置信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveConfig_Click(object sender, EventArgs e)
{
//启动当前应用程序可执行文件exe的路径
string R_startPath = Application.ExecutablePath;
if (CheckState.Checked == true)
{
#region 添加开机启动
try
{
RegistryKey R_local = Registry.LocalMachine;

//查找到要添加到的注册表项
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
//添加注册表项
R_run.SetValue("StartupAppyatou1019", R_startPath);

R_run.Close();
R_local.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
#endregion
}
else
{
#region 取消开机启动
try
{
RegistryKey R_local = Registry.LocalMachine; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
//删除相应的注册表项
R_run.DeleteValue("StartupAppyatou1019",false);
R_run.Close();
R_local.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
#endregion
}
}

/// <summary>
/// 判断开机启动项是否已存在
/// </summary>
/// <returns></returns>
private bool IsRegKeIsExt()
{
bool IsExt = false;

RegistryKey R_local = Registry.LocalMachine;
//查找到要添加到的注册表项
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

//获得注册表项的值
object _obj=R_run.GetValue("StartupAppyatou1019");
R_run.Close();
R_local.Close();

if(_obj!=null)
{
IsExt=true;
}
return IsExt;
}

 注意:

     在Win7 系统中需要以管理员身份运行程序(可以直接设置程序始终以管理员身份运行),否则无权对注册表进行更改

原文地址:https://www.cnblogs.com/luowanli/p/markeluo_Winfrom_Startup.html