using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Vinno.IUS.Common.Log; namespace ProcessDaemonTool { public class AutoStartupHelper { private const string Wow32RunPath = @"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; private const string Wow64RunPath = @"Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run"; private static readonly string AppExecutePath = Process.GetCurrentProcess().MainModule.FileName; private static readonly string KeyPath = Environment.Is64BitProcess ? Wow64RunPath : Wow32RunPath; public static bool Register(string appName) { Logger.WriteLineInfo($"Regist app {appName} with path {AppExecutePath} to regedit."); try { if (IsRegistered(appName)) { return true; } var keyPath = Environment.Is64BitProcess ? Wow64RunPath : Wow32RunPath; var registerRunKey = Registry.LocalMachine.OpenSubKey(keyPath, true) ?? Registry.LocalMachine.CreateSubKey(keyPath); if (registerRunKey != null) { registerRunKey.SetValue(appName, AppExecutePath); registerRunKey.Close(); } return true; } catch (Exception ex) { Logger.WriteLineError($"Regist application {appName} with path {AppExecutePath} failed, ex:{ex}"); return false; } } public static bool Unregister(string appName) { try { if (!IsRegistered(appName)) { return true; } var keyPath = Environment.Is64BitProcess ? Wow64RunPath : Wow32RunPath; var registerRunKey = Registry.LocalMachine.OpenSubKey(keyPath, true); if (registerRunKey != null) { registerRunKey.DeleteValue(appName); registerRunKey.Close(); } return true; } catch (Exception ex) { Logger.WriteLineError($"Unregist application {appName} failed, ex:{ex}"); return false; } } private static bool IsRegistered(string appName) { var executablePath = string.Empty; try { var path = Environment.Is64BitProcess ? Wow64RunPath : Wow32RunPath; var registryRunKey = Registry.LocalMachine.OpenSubKey(path); if (registryRunKey != null) { executablePath = registryRunKey.GetValue(appName) as string; registryRunKey.Close(); } } catch (Exception ex) { Logger.WriteLineError($"Get application {appName} value failed, ex:{ex}"); } Logger.WriteLineDebug($"AuoStartup executablePath - {executablePath}"); return !string.IsNullOrEmpty(executablePath) && executablePath == AppExecutePath; } } }