最近做的項目需要在注冊表中記錄一些用戶設置,方便在程序下次啟動時讀取設置,應用上次用戶保存的設置,挺簡單的。
寫出來,方便記憶,以後要用,可以直接改改就能用。
using System; namespace Backend { public class RegistryStorage { public static PageVisibility OpenAfterStart() { Microsoft.Win32.RegistryKey registryKey; PageVisibility visibility = PageVisibility.Visible; // HKCU\Software\RegeditStorage registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\RegistryStorage"); if (registryKey != null) { visibility = (string)registryKey.GetValue("PageVisibility") == PageVisibility.Hide.ToString() ? PageVisibility.Hide : PageVisibility.Visible; registryKey.Close(); } return visibility; } public static void SaveBeforeExit(PageVisibility visibility) { Microsoft.Win32.RegistryKey registryKey; // HKCU\Software\RegeditStorage registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\RegistryStorage"); registryKey.SetValue("PageVisibility", visibility.ToString()); registryKey.Close(); } } public enum PageVisibility { Visible, Hide } }
代碼很容易理解,下面添加一點代碼來測試一下。
using System; using System.Diagnostics; namespace Backend.Test { class Program { static void Main(string[] args) { // 存值 RegistryStorage.SaveBeforeExit(PageVisibility.Hide); // 取值 PageVisibility visibility = RegistryStorage.OpenAfterStart(); // 驗證 Debug.Assert(visibility == PageVisibility.Hide); // 存值 RegistryStorage.SaveBeforeExit(PageVisibility.Visible); // 取值 visibility = RegistryStorage.OpenAfterStart(); // 驗證 Debug.Assert(visibility == PageVisibility.Visible); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } }
最後,上一張修改後的注冊表截圖:
查看本欄目