From 092d1168ff1c1690c1e627650b4b029430ff5feb Mon Sep 17 00:00:00 2001 From: Gang Zhuo Date: Thu, 8 Oct 2015 06:33:02 -0400 Subject: [PATCH] start all instances on boot under portable model --- .../Controller/System/AutoStartup.cs | 44 ++++++++++++++++--- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/shadowsocks-csharp/Controller/System/AutoStartup.cs b/shadowsocks-csharp/Controller/System/AutoStartup.cs index 36ad775f..a2ad21c1 100644 --- a/shadowsocks-csharp/Controller/System/AutoStartup.cs +++ b/shadowsocks-csharp/Controller/System/AutoStartup.cs @@ -6,21 +6,23 @@ namespace Shadowsocks.Controller { class AutoStartup { + static string Key = "Shadowsocks_" + Application.StartupPath.GetHashCode(); + public static bool Set(bool enabled) { + RegistryKey runKey = null; try { string path = Application.ExecutablePath; - RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); + runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (enabled) { - runKey.SetValue("Shadowsocks", path); + runKey.SetValue(Key, path); } else { - runKey.DeleteValue("Shadowsocks"); + runKey.DeleteValue(Key); } - runKey.Close(); return true; } catch (Exception e) @@ -28,20 +30,39 @@ namespace Shadowsocks.Controller Logging.LogUsefulException(e); return false; } + finally + { + if (runKey != null) + { + try { runKey.Close(); } + catch (Exception e) + { Logging.LogUsefulException(e); } + } + } } public static bool Check() { + RegistryKey runKey = null; try { string path = Application.ExecutablePath; - RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); + runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); string[] runList = runKey.GetValueNames(); - runKey.Close(); foreach (string item in runList) { - if (item.Equals("Shadowsocks")) + if (item.Equals(Key)) return true; + else if (item.Equals("Shadowsocks")) // Compatibility with older versions + { + string value = Convert.ToString(runKey.GetValue(item)); + if (path.Equals(value, StringComparison.InvariantCultureIgnoreCase)) + { + runKey.DeleteValue(item); + runKey.SetValue(Key, path); + return true; + } + } } return false; } @@ -50,6 +71,15 @@ namespace Shadowsocks.Controller Logging.LogUsefulException(e); return false; } + finally + { + if (runKey != null) + { + try { runKey.Close(); } + catch(Exception e) + { Logging.LogUsefulException(e); } + } + } } } }