C# 将应用程序通过注册表设置开机启动项

转载自C# 将当前应用程序写入到注册表开机启动项中

//设置开机启动
private void AutoRunAfterStart()
 {
    //获取当前应用程序的路径
    string localPath = Application.ExecutablePath;
    if (!System.IO.File.Exists(localPath))//判断指定文件是否存在
        return;
    RegistryKey reg = Registry.LocalMachine;
    RegistryKey run = reg.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
    //判断注册表中是否存在当前名称和值
    if (run.GetValue("ControlPanasonic.exe") == null)
    {
        try
        {
            run.SetValue("ControlPanasonic.exe", localPath);
            MessageBox.Show("  当前应用程序已成功写入注册表!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            reg.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString(), "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

}
//删除注册表钟的特定值
//取消开机启动
private void DeleteSubKey()
 {
    RegistryKey reg = Registry.LocalMachine;
    RegistryKey run = reg.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);
    try
    {
        run.DeleteValue("ControlPanasonic.exe");
        MessageBox.Show("  当前应用程序已成功从注册表中删除!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        reg.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString(), "温馨提示",MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

现在就上面的代码做一些简要的分析,RegistryKey reg = Registry.LocalMachine;RegistryKey run = reg.CreateSubKey(@”SOFTWARE\Microsoft \Windows \CurrentVersion\Run”);这两句代码的核心是获取RegistryKey 的对象,然后通过SetValue以及DeleteValue将当前的exe写入到注册表中,这样就能够永久去保存当前的键值对,从而确定开机启动项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值