반응형
    public class StartupHelper
    {
        private string programName;
        private string exeFilePath;
        private const string AutoRunRegistryKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

        public StartupHelper(string programName, string exeFilePath)
        {
            this.programName = programName;
            this.exeFilePath = string.Format($"\"{exeFilePath}\"");
        }

        public bool IsReregistered()
        {
            bool isReregistered = false;
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

            try
            {
                if (registryKey.GetValue(programName) == null) return false;

                string value = (string)registryKey.GetValue(programName);

                isReregistered = value == exeFilePath;
            }
            catch (Exception)
            {
                isReregistered = false;
            }
            finally
            {
                registryKey.Close();
            }

            return isReregistered;
        }

        public void RegisterStartUp()
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

            registryKey.SetValue(programName, exeFilePath);
            registryKey.Close();
        }

        public void UnregisterStartUp()
        {
            if (!IsReregistered()) return;

            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

            registryKey.DeleteValue(programName, false);
            registryKey.Close();
        }
    }
        private void RegisterStartUp()
        {
            Assembly assembly = Assembly.GetEntryAssembly();

            string path = assembly.Location;
            string name = Path.GetFileNameWithoutExtension(path);

            startup = new StartupHelper(name, path);

            if (!startup.IsReregistered())
            {
                startup.RegisterStartUp();
            }
        }
반응형

'[====== Development ======] > C#' 카테고리의 다른 글

[C#] Exception으로 인한 죽는것 방지  (0) 2021.08.13
[C#] 중복 실행 방지  (0) 2021.08.13
Delete File  (0) 2021.08.06
파일 복사시 Unique 이름으로 저장  (0) 2021.08.06
C# -> C++ MFC SendMessage string  (0) 2021.08.05

+ Recent posts