Files

62 lines
1.9 KiB
C#
Raw Permalink Normal View History

2026-09-26 12:11:20 +07:00
using Microsoft.Win32;
namespace HearingProtector;
internal sealed record AppSettings(double MinPercent, double FullDecayMinutes)
{
public static AppSettings Default => new(1.0, 30.0);
}
internal static class SettingsStore
{
private const string KeyPath = @"Software\HearingProtector";
private const string ValueMin = "MinPercent";
private const string ValueDecay = "FullDecayMinutes";
public static AppSettings Load()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(KeyPath);
if (key is null) return AppSettings.Default;
double min = ReadDouble(key, ValueMin, AppSettings.Default.MinPercent);
double decay = ReadDouble(key, ValueDecay, AppSettings.Default.FullDecayMinutes);
if (min < 0 || min > 50) min = AppSettings.Default.MinPercent;
if (decay < 30 || decay > 360) decay = AppSettings.Default.FullDecayMinutes;
return new AppSettings(min, decay);
}
catch
{
return AppSettings.Default;
}
}
public static void Save(AppSettings s)
{
try
{
using var key = Registry.CurrentUser.CreateSubKey(KeyPath, writable: true);
if (key is null) return;
key.SetValue(ValueMin, s.MinPercent, RegistryValueKind.String);
key.SetValue(ValueDecay, s.FullDecayMinutes, RegistryValueKind.String);
key.DeleteValue("PollMs", throwOnMissingValue: false);
}
catch { }
}
private static double ReadDouble(RegistryKey key, string name, double fallback)
{
var raw = key.GetValue(name);
return raw switch
{
string s when double.TryParse(s, System.Globalization.CultureInfo.InvariantCulture,
out var d) => d,
double d => d,
_ => fallback,
};
}
}