學習DOTS之調用註冊表

/////////////////////////////////////////////////////////////////////////////////////////

一、註冊表操作簡介

Registry RegistryKey 提供了操作註冊表的接口

RegistryValueKind:用於指定操作註冊表的數據類型

一.註冊表巢

     在註冊表中,最上面的節點是註冊表巢(registry hive)。

  •      HKEY_CLASSES_ROOT(HKCR)    包含系統文件類型的細節,以及應用程序可以打開的文件類型,它還包含所有COM組件的註冊信息。
  •      HKEY_CURRENT_USER(HKCU)    包含用戶目前登陸的機器的用戶配置,包括桌面設置、環境變量、網絡和打印機連接和其他定義用戶操作環境的變量。
  •      HKEY_LOCAL_MACHINE(HKLM)    是一個很大的巢,其中包含所有安裝到機器上的軟件和硬件的信息。
  •      HKEY_USERS(HKUSR)                包含所有用戶的用戶配置。
  •      HKEY_CURRENT_CONFIG(HKCF)  包含機器上硬件的信息。

Registry靜態類

Registry類封裝了註冊表的七個基本主鍵:

  • Registry.ClassesRoot 對應於HKEY_CLASSES_ROOT主鍵
  • Registry.CurrentUser:對應於HKEY_CURRENT_USER主鍵
  • Registry.LocalMachine:對應於 HKEY_LOCAL_MACHINE主鍵
  • Registry.User:對應於 HKEY_USER主鍵
  • Registry.CurrentConfig:對應於HEKY_CURRENT_CONFIG主鍵
  • Registry.DynDa :對應於HKEY_DYN_DATA主鍵
  • Registry.PerformanceData:對應於HKEY_PERFORMANCE_DATA主鍵

const string KeyName = "HKEY_CURRENT_USER\\Example";

Registry.SetValue(keyName, "", 5280);//默認名稱

Registry.SetValue(keyName, "TestLong", 1234567, RegistryValueKind.QWord);

int i = (int)Registry.GetValue(keyName, "", -1);//默認值

long l = (long)Registry.GetValue(keyName, "TestLong", long.MinValue);

RegistryKey

RegistryKey類封裝了對註冊表的基本操作。包括讀、寫、刪等操作的常用函數:

  • Name:鍵的名稱(只讀)
  • SubKeyCount:鍵的子鍵個數
  • ValueCount:鍵包含的值的個數
  • Close():關閉鍵
  • CreateSubKey():創建給定名稱的子鍵
  • DeleteSubKey():刪除指定的子鍵
  • DeleteSubKeyTree():遞歸刪除子鍵及其所有的子鍵
  • DeleteValue():從鍵中刪除一個指定的值
  • GetAccessControl():返回指定註冊表鍵的訪問控制表
  • GetSubKeyNames():返回包含子鍵名稱的字符串數組
  • GetValue():返回指定的值
  • GetValueKind();返回指定的值,檢索其註冊表數據類型
  • GetValueNames():返回一個包含所有鍵值名稱的字符串數組
  • OpenSubKey():返回表示給定子鍵的RegistryKey實例引用
  • SetAccessControl():把訪問控制表(ACL)應用於指定的註冊表鍵
  • SetValue();設置指定的值

 

二、註冊表項的創建、打開、刪除

1、創建,CreateSubKey

//使用CreateSubKey()在SOFTWARE下創建子項test

RegistryKey hklm = Registry.LocalMachine;

RegistryKey hkSoftWare = hklm.CreateSubKey(@"SOFTWARE\test");

hklm.Close();

hkSoftWare.Close();

2、打開,OpenSubKey

//使用OpenSubKey()打開項,獲得RegistryKey對象,當路徑不存在時,爲Null。第二個參數爲true,表示可寫,可讀,可刪;省略時只能讀。

RegistryKey hklm = Registry.LocalMachine;

RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test",true);

hklm.Close();

hkSoftWare.Close();

3、刪除,DeleteSubKey

//主要用到了DeleteSubKey(),刪除test項

RegistryKey hklm = Registry.LocalMachine;

hklm.DeleteSubKey(@"SOFTWARE\test", true);  //爲true時,刪除的註冊表不存在時拋出異常;當爲false時不拋出異常。

hklm.Close();

 

三、註冊表鍵值的創建、打開和刪除

1、創建,SetValue

//主要用到了SetValue(),表示在test下創建名稱爲Name,值爲RegistryTest的鍵值。第三個參數表示鍵值類型,省略時,默認爲字符串

RegistryKey hklm = Registry.LocalMachine;

RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test",true);

hkSoftWare.SetValue("Name", "RegistryTest", RegistryValueKind.String);

hklm.Close();

hkSoftWare.Close();

2、打開,GetValue

//主要用到了GetValue(),獲得名稱爲"Name"的鍵值

RegistryKey hklm = Registry.LocalMachine;

RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test", true);

string sValue = hkSoftWare.GetValue("Name").ToString();

hklm.Close();

hkSoftWare.Close();

3、刪除,DeleteValue

//主要用到了DeleteValue(),表示刪除名稱爲"Name"的鍵值,第二個參數表示是否拋出異常

RegistryKey hklm = Registry.LocalMachine;

RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test", true);

hkSoftWare.DeleteValue("Name", true);

hklm.Close();

hkSoftWare.Close();

 

四、例子:

1、判斷註冊表項、註冊表鍵值是否存在

 

//判斷註冊表項是否存在

        private bool IsRegistryKeyExist(string sKeyName)

        {

            string[] sKeyNameColl;

            RegistryKey hklm = Registry.LocalMachine;

            RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE");

            sKeyNameColl = hkSoftWare.GetSubKeyNames(); //獲取SOFTWARE下所有的子項

            foreach (string sName in sKeyNameColl)

            {

                if (sName == sKeyName)

                {

                    hklm.Close();

                    hkSoftWare.Close();

                    return true;

                }

            }

            hklm.Close();

            hkSoftWare.Close();

            return false;

        }

 

 

        //判斷鍵值是否存在

        private bool IsRegistryValueNameExist(string sValueName)

        {

            string[] sValueNameColl;

            RegistryKey hklm = Registry.LocalMachine;

            RegistryKey hkTest = hklm.OpenSubKey(@"SOFTWARE\test");

            sValueNameColl = hkTest.GetValueNames(); //獲取test下所有鍵值的名稱

            foreach (string sName in sValueNameColl)

            {

                if (sName == sValueName)

                {

                    hklm.Close();

                    hkTest.Close();

                    return true;

                }

            }

            hklm.Close();

            hkTest.Close();

            return false;

        }

 

2、程序自啓動程序

 

//開啓程序自啓動

string path = Application.ExecutablePath;

RegistryKey rk = Registry.LocalMachine;

RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");

rk2.SetValue("JcShutdown", path);

rk2.Close();

rk.Close();

 

 

 

//關閉程序自啓動

string path = Application.ExecutablePath;

RegistryKey rk = Registry.LocalMachine;

RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");

rk2.DeleteValue("JcShutdown", false);

rk2.Close();

rk.Close();

 

 

五、打開遠程註冊表

RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,"192.168.0.2");

RegistryKey softwareKey = key.OpenSubKey("software\\test");

softwareKey.Close();

baseKey.Close();

/////////////////////////////////////////////////////////////////////////////////////////////

 

using System;

using System.Collections;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using UnityEditor;

using UnityEngine;

 

public class ECSSetup : Editor {

#if UNITY_EDITOR_WIN

    private static string unityInstallDir = string.Empty;

    private const string unityTemplateDir = @"Editor\Data\Resources\ScriptTemplates";

    private const string unityRegistryKey = @"Software\Unity Technologies\Installer\Unity\";

    private const string unityRegistryValue = @"Location x64";

#elif UNITY_EDITOR_OSX

    private const string unityInstallDir = @"/Applications/Unity/Unity.app/Contents";

    private const string unityTemplateDir = @"Resources/ScriptTemplates";

#else

    private const string unityInstallDir = @"/opt/Unity";

    private const string unityTemplateDir = @"Editor/Data/Resources/ScriptTemplates";

#endif

    private static bool enableTemplateValidation = true;

 

    private static string TemplatePath {

        get {

            #if UNITY_EDITOR_WIN

            if (string.IsNullOrEmpty(unityInstallDir)) {

                //var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(unityRegistryKey, false);

                //unityInstallDir = (string)key.GetValue(unityRegistryValue);

            }

            #endif

            return Path.Combine(unityInstallDir, unityTemplateDir);

        }

    }

 

    static readonly string[] files = {

            "91-ECS__Wrapped Component Class-NewComponent.cs",

            "91-ECS__Component Class-NewComponent.cs",

            "91-ECS__Wrapped Component Struct-NewComponent.cs",

            "91-ECS__Component Struct-NewComponent.cs",

            "91-ECS__System-NewSystem.cs",

            "91-ECS__ECSController-NewECSController.cs",

        };

 

    [MenuItem("ECS/Install Templates", isValidateFunction: true)]

    private static bool ValidateInstallTemplates() {

        if (!enableTemplateValidation)

            return true;

 

        // Only allow installation if *none* of the files exist

        if (files.All(s => !File.Exists(Path.Combine(TemplatePath, s + ".txt"))) && CanCreateFileInTemplates())

            return true;

 

        return false;

    }

 

    [MenuItem("ECS/Uninstall Templates", isValidateFunction: true)]

    private static bool ValidateUninstallTemplates() {

        if (!enableTemplateValidation)

            return true;

 

        // To make sure we can clean up properly, check if *any* of the template files exist

        if (files.Any(s => File.Exists(Path.Combine(TemplatePath, s + ".txt"))) && CanCreateFileInTemplates())

            return true;

 

        return false;

    }

 

    private static bool CanCreateFileInTemplates() {

        try {

            var testfile = Path.Combine(TemplatePath, ".test");

            var stream = File.Create(testfile);

            stream.Close();

            File.Delete(testfile);

            return true;

        }

        catch (UnauthorizedAccessException)

        {

            return false;

        }

    }

 

    [MenuItem("ECS/Install Templates")]

    private static void InstallTemplates() {

        try {

            var unityDir = TemplatePath;

            if(!Directory.Exists(unityDir))

            {

                EditorUtility.DisplayDialog("ECS Installation", "Setup not supported for your OS!\n Please copy the template folder content manually to:\n<UnityInstall>/" + unityTemplateDir + "\n\n and restart unity!", "ok");          

                return;

            }

 

            foreach (var file in files) {

                var assetGUID = AssetDatabase.FindAssets(file)[0];

                var filePath = AssetDatabase.GUIDToAssetPath(assetGUID);

                File.Copy(Path.Combine(Directory.GetParent(Application.dataPath).FullName, filePath), Path.Combine(unityDir, Path.GetFileName(filePath)), true);

                //var filePath = AssetDatabase.GetAssetPath();

            }

            EditorUtility.DisplayDialog("ECS Setup", "Installation completed!\nPlease restart unity to access all functionalities!", "ok");

        }

        catch (UnauthorizedAccessException)

        {

            EditorUtility.DisplayDialog("ECS Setup", "You need access privileges to the Unity install folder.\nStart Unity as Administrator and try again.", "ok");

        }

        catch (Exception ex)

        {

            EditorUtility.DisplayDialog("ECS Setup", "SSomething went wrong!\n\n Error:\n" + ex.Message, "ok");

        }

    }

 

    [MenuItem("ECS/Uninstall Templates")]

    private static void UninstallECS() {

        string unityDir = TemplatePath;

        if(!Directory.Exists(unityDir))

        {

            EditorUtility.DisplayDialog("ECS Uninstallation", "Uninstallation not supported for your OS!\n Please delete the template folder content manually from:\n<Unityinstall>/"+ unityTemplateDir + "\n\n and restart unity!", "ok");          

            return;

        }

 

        try {

            foreach (var file in files)

            {

                File.Delete(Path.Combine(unityDir, file + ".txt"));

            }

            EditorUtility.DisplayDialog("ECS Uninstallation", "Uninstallation completed!\nPlease restart unity!", "ok");

        }

        catch (UnauthorizedAccessException)

        {

            EditorUtility.DisplayDialog("ECS Setup", "You need access privileges to the Unity install folder.\nStart Unity as Administrator and try again.", "ok");

        }

        catch (Exception ex)

        {

            EditorUtility.DisplayDialog("ECS Setup", "SSomething went wrong!\n\n Error:\n" + ex.Message, "ok");

        }

    }

 

    [MenuItem("ECS/Enable Visual Debugging")]

    private static void EnableVisualDebugging() {

        foreach (BuildTargetGroup buildTarget in Enum.GetValues(typeof(BuildTargetGroup))) {

            if (buildTarget == BuildTargetGroup.Unknown) {

                continue;

            }

            var scriptSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget).Split(';').Where(x => !string.IsNullOrEmpty(x)).ToList();

            if (!scriptSymbols.Contains("ECS_DEBUG")) {

                scriptSymbols.Add("ECS_DEBUG");

            }

 

            try {

                PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, string.Join(";", scriptSymbols.ToArray()));

            } catch { }

        }

    }

 

    [MenuItem("ECS/Enable Visual Debugging", isValidateFunction:true)]

    private static bool ValidateEnableVisualDebugging() {

       return !PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone).Contains("ECS_DEBUG");

    }

 

    [MenuItem("ECS/Disable Visual Debugging")]

    private static void DisableVisualDebugging() {

        foreach (BuildTargetGroup buildTarget in Enum.GetValues(typeof(BuildTargetGroup))) {

            if (buildTarget == BuildTargetGroup.Unknown) {

                continue;

            }

            var scriptSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget).Split(';').Where(x => !string.IsNullOrEmpty(x)).ToList();

            scriptSymbols.Remove("ECS_DEBUG");

            try {

                PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, string.Join(";", scriptSymbols.ToArray()));

            } catch { }

        }

    }

 

    [MenuItem("ECS/Disable Visual Debugging", isValidateFunction: true)]

    private static bool ValidateDisableVisualDebugging() {

        return PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone).Contains("ECS_DEBUG");

    }

   

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章