123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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;
- }
- }
- }
|