unity程序开机自启的方法不只这一种,我觉得这个好用,就记下了。
直接上代码吧:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using Microsoft.Win32;
/*
*
* Writer:June
*
* Date: 2019.12.5
*
* Function:通过注册表让程序开机自启
*
* Remarks: win+R打开运行。 输入 regedit 打开注册表,按照自己设置的_targetPath目标项路径依次打开,就可看到新建的键值
*
*/
public class Regeditkey : MonoBehaviour
{
public Button _setupStartupButton;
public Button _cancelStartupButton;
/// <summary>
/// //获取当前进程
/// </summary>
string _path;
/// <summary>
/// 注册表中的名称
/// </summary>
string _nameInRegistry = "MyUnityProject";
/// <summary>
/// 目标项路径
/// </summary>
string _targetPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
private void Awake()
{
_path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
}
private void OnEnable()
{
//按钮事件监听
_setupStartupButton.onClick.AddListener(OnSetupStartupButtonClick);
_cancelStartupButton.onClick.AddListener(OnCancelStartupButtonClick);
}
private void OnDisable()
{
//移除按钮事件监听
_setupStartupButton.onClick.RemoveListener(OnSetupStartupButtonClick);
_cancelStartupButton.onClick.RemoveListener(OnCancelStartupButtonClick);
}
/// <summary>
/// 开机自启
/// </summary>
private void OnSetupStartupButtonClick()
{
// 提示,需要更改注册表
try
{
RegistryKey rgkRun = Get_RegistryKey(_targetPath);
//设置键值
rgkRun.SetValue(_nameInRegistry, _path);
}
catch { Debug.LogError(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); }
finally{ RegeditkeyDebugLog(); }
}
/// <summary>
/// 关闭自启
/// </summary>
private void OnCancelStartupButtonClick()
{
// 提示,需要更改注册表
try
{
RegistryKey rgkRun = Get_RegistryKey(_targetPath);
//删除键值
rgkRun.DeleteValue(_nameInRegistry, false);
}
catch { Debug.LogError("Error!"); }
finally { RegeditkeyDebugLog(); }
}
/// <summary>
/// 输出日志:自启动的状态
/// </summary>
private void RegeditkeyDebugLog()
{
RegistryKey rgkRun = Get_RegistryKey(_targetPath);
//判断是否写入
if (rgkRun.GetValue(_nameInRegistry) == null) Debug.LogError("自启动为关闭");
else Debug.LogError("自启动为打开");
}
/// <summary>
/// 判断注册表文件项是否存在,不存在则创建
/// </summary>
/// <param name="_targetPath">目标路径</param>
/// <returns></returns>
private RegistryKey Get_RegistryKey(string _targetPath)
{
RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey(_targetPath, true);
if (rgkRun == null)
{
rgkRun = Registry.LocalMachine.CreateSubKey(_targetPath);
}
return rgkRun;
}
}
注意:.net版本过低也会报错,引用了win32命名空间也取不到Registry这个类!
运行后,如果打开注册表,没看见有自己设置的键值,那就以管理员的身份运行程序就没什么问题的了!