C# 代码控制程序自启

C# 通过添加注册表的方式实现程序开机自启

开机自启与检查

实现代码

internal class StartUp
{
    /// <summary>  
    /// 修改程序在注册表中的键值  
    /// </summary>  
    /// <param name="isAuto">true:开机启动,false:不开机自启</param> 
    public void AutoStart(bool isAuto = true)
    {
        if (isAuto == true)
        {
            RegistryKey R_local = Registry.CurrentUser;
            RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            R_run.SetValue("人名币大小写转换助手", System.Windows.Forms.Application.ExecutablePath);
            R_run.Close();
            R_local.Close();
        }
        else
        {
            RegistryKey R_local = Registry.CurrentUser;
            RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            R_run.DeleteValue("人名币大小写转换助手", false);
            R_run.Close();
            R_local.Close();
        }
    }
​
    /// <summary>
    /// 判断注册键值对是否存在,即是否处于开机启动状态
    /// </summary>
    /// <param name="keyName">键值名</param>
    /// <returns></returns>
    public bool IsExistKey(string keyName = "人名币大小写转换助手")
    {
        try
        {
            bool _exist = false;
            RegistryKey local = Registry.CurrentUser;
            RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
            if (runs == null)
            {
                RegistryKey key2 = local.CreateSubKey("SOFTWARE");
                RegistryKey key3 = key2.CreateSubKey("Microsoft");
                RegistryKey key4 = key3.CreateSubKey("Windows");
                RegistryKey key5 = key4.CreateSubKey("CurrentVersion");
                RegistryKey key6 = key5.CreateSubKey("Run");
                runs = key6;
            }
            string[] runsName = runs.GetValueNames();
            foreach (string strName in runsName)
            {
                if (strName.ToUpper() == keyName.ToUpper())
                {
                    _exist = true;
                    return _exist;
                }
            }
            return _exist;
​
        }
        catch
        {
            return false;
        }
    }
}

使用

// 判断是否自启
private void Form1_Load(object sender, EventArgs e)
{
    checkBox1.Checked = new StartUp().IsExistKey();
}
// 打开/关闭自启
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBox1.Checked)
    {
        StartUp startUp = new StartUp();
        startUp.AutoStart(true);
    }
    else
    {
        StartUp startUp = new StartUp();
        startUp.AutoStart(false);
    }
}

LICENSED UNDER CC BY-NC-SA 4.0
Comment