在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
最近做的项目需要在注册表中记录一些用户设置,方便在程序下次启动时读取设置,应用上次用户保存的设置,挺简单的。 写出来,方便记忆,以后要用,可以直接改改就能用。 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\RegeditStorage 13 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\RegeditStorage 29 registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\RegistryStorage"); 30 registryKey.SetValue("PageVisibility", visibility.ToString()); 31 registryKey.Close(); 32 } 33 } 34 35 public enum PageVisibility 36 { 37 Visible, 38 Hide 39 } 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 } 最后,上一张修改后的注册表截图:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论