Browse Source

Fix RunOnStartup conflict with multiple exes

If you tried to get multiple clocks to run on startup, they would overwrite each other.
Daniel Chalmers 2 years ago
parent
commit
18f101c72c
1 changed files with 15 additions and 2 deletions
  1. 15 2
      DesktopClock/SettingsHelper.cs

+ 15 - 2
DesktopClock/SettingsHelper.cs

@@ -20,11 +20,24 @@ public static class SettingsHelper
 
     public static void SetRunOnStartup(bool runOnStartup)
     {
+        var exePath = App.ResourceAssembly.Location;
+        var keyName = GetSha256Hash(exePath);
         using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
 
         if (runOnStartup)
-            key?.SetValue("DesktopClock", App.ResourceAssembly.Location);
+            key?.SetValue(keyName, exePath); // Use the path as the name so we can handle multiple exes, but hash it or Windows won't like it.
         else
-            key?.DeleteValue("DesktopClock", false);
+            key?.DeleteValue(keyName, false);
+    }
+
+    internal static string GetSha256Hash(string text)
+    {
+        if (string.IsNullOrEmpty(text))
+            return string.Empty;
+
+        using var sha = new System.Security.Cryptography.SHA256Managed();
+        var textData = System.Text.Encoding.UTF8.GetBytes(text);
+        var hash = sha.ComputeHash(textData);
+        return BitConverter.ToString(hash).Replace("-", string.Empty);
     }
 }