最近做的项目需要在注册表中记录一些用户设置,方便在程序下次启动时读取设置,应用上次用户保存的设置,挺简单的。
写出来,方便记忆,以后要用,可以直接改改就能用。
1 using System; 2 3 namespace Backend 4 { 5 public class RegistryStorage 6 { 7 public static PageVisibility OpenAfterStart() 8 { 9 Microsoft.Win32.RegistryKey registryKey;10 PageVisibility visibility = PageVisibility.Visible;11 12 // HKCU\Software\RegeditStorage13 registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\RegistryStorage");14 if (registryKey != null)15 {16 visibility = (string)registryKey.GetValue("PageVisibility") == PageVisibility.Hide.ToString() ?17 PageVisibility.Hide : PageVisibility.Visible;18 registryKey.Close();19 }20 21 return visibility;22 }23 24 public static void SaveBeforeExit(PageVisibility visibility)25 {26 Microsoft.Win32.RegistryKey registryKey;27 28 // HKCU\Software\RegeditStorage29 registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\RegistryStorage");30 registryKey.SetValue("PageVisibility", visibility.ToString());31 registryKey.Close();32 }33 }34 35 public enum PageVisibility36 { 37 Visible,38 Hide39 }40 }
代码很容易理解,下面添加一点代码来测试一下。
1 using System; 2 using System.Diagnostics; 3 4 namespace Backend.Test 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 {10 // 存值 11 RegistryStorage.SaveBeforeExit(PageVisibility.Hide);12 // 取值13 PageVisibility visibility = RegistryStorage.OpenAfterStart();14 // 验证15 Debug.Assert(visibility == PageVisibility.Hide);16 17 18 // 存值19 RegistryStorage.SaveBeforeExit(PageVisibility.Visible);20 // 取值21 visibility = RegistryStorage.OpenAfterStart();22 // 验证23 Debug.Assert(visibility == PageVisibility.Visible);24 25 Console.WriteLine("Press any key to exit.");26 Console.ReadKey();27 }28 }29 }
最后,上一张修改后的注册表截图:
版权归博客园和作者共有。.NET类库源码参考 扣丁格鲁 www.projky.com,转载请注明出处。