天天看点

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写入到注册表中,这样就能够永久去保存当前的键值对,从而确定开机启动项。