using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Microsoft.Win32; using UnityEngine.Events; using System.Security.Principal; using Cysharp.Threading.Tasks; namespace BITKit { public class RegistryRunAPP : MonoBehaviour { [Header(Constant.Header.Settings)] [SerializeReference,SubclassSelector] private IReference subKey; [SerializeReference,SubclassSelector] private string executablePath; private bool executeOnStart; [Header(Constant.Header.Events)] public UnityEvent onSuccess = new(); public UnityEvent onfailure = new(); public void Excute() { try { Debug.Log("正在启动注册函数"); var path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; var result = RegisterAppKey(subKey.Value, path); Debug.Log($"正在注册启动:{subKey}:{path}"); if (result) { onSuccess.Invoke(true); } else { onfailure.Invoke(); } } catch (System.Exception e) { Debug.LogError(e); Debug.LogException(e,this); onfailure.Invoke(); } } async void Start() { await UniTask.Yield(); if (executeOnStart) Excute(); } private static bool RegisterAppKey(string keyName, string value) { #if UNITY_WEBGL Debug.LogWarning("在WebGL上无法注册启动方式"); return false; #else try { RegistryKey registryKey = Registry.ClassesRoot; var fKey = registryKey.OpenSubKey(keyName, true) ?? registryKey.CreateSubKey(keyName); fKey.SetValue("", value); fKey.SetValue("", keyName); var defaultIconKey = fKey.OpenSubKey("DefaultIcon", true) ?? fKey.CreateSubKey("DefaultIcon"); if (defaultIconKey != null) { defaultIconKey.SetValue("", value + ",1"); } var shellKey = fKey.OpenSubKey("shell", true) ?? fKey.CreateSubKey("shell"); var openKey = shellKey.OpenSubKey("open", true) ?? shellKey.CreateSubKey("open"); var commandKey = openKey.OpenSubKey("command", true) ?? openKey.CreateSubKey("command"); if (commandKey != null) { commandKey.SetValue("", "\"" + value + "\"" + " \"%1\""); } fKey.SetValue("URL Protocol", value); fKey.Close(); Debug.Log("已完成程序启动注册"); return true; } catch (Exception ex) { Debug.LogException(ex); return false; } #endif } } }