WPF 将程序设为开启自启 (注册表实现) 您所在的位置:网站首页 将程序设为开机启动 WPF 将程序设为开启自启 (注册表实现)

WPF 将程序设为开启自启 (注册表实现)

2024-07-17 05:40| 来源: 网络整理| 查看: 265

1.写入或删除注册表键值对,即设为开机启动或开机不启动 2.判断注册键值对是否存在,即是否处于开机启动状态 3.将应用程序设为或不设为开机启动

/// /// 将本程序设为开启自启 /// /// 自启开关 /// public static Boolean SetMeStart(Boolean OnOff) {     String AppName = Process.GetCurrentProcess().MainModule.ModuleName;     String AppPath = Process.GetCurrentProcess().MainModule.FileName;     return SetAutoStart(OnOff, AppName, AppPath); } /// /// 将应用程序设为或不设为开机启动 /// /// 自启开关 /// 应用程序名 /// 应用程序完全路径 public static Boolean SetAutoStart(Boolean OnOff, String AppName, String AppPath) {     Boolean isOk = true;     //如果从没有设为开机启动设置到要设为开机启动     if (!IsExistKey(AppName) && OnOff)     {         isOk = SelfRunning(OnOff, AppName, @AppPath);     }     //如果从设为开机启动设置到不要设为开机启动     else if (IsExistKey(AppName) && !OnOff)     {         isOk = SelfRunning(OnOff, AppName, @AppPath);     }     return isOk; } /// /// 判断注册键值对是否存在,即是否处于开机启动状态 /// /// 键值名 /// private static Boolean IsExistKey(String KeyName) {     try     {         Boolean _exist = false;         RegistryKey local = Registry.LocalMachine;         RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);         if (runs == null)         {             RegistryKey key2 = local.CreateSubKey("SOFTWARE");             RegistryKey key3 = key2.CreateSubKey("Microsoft");             RegistryKey key4 = key3.CreateSubKey("Windows");             RegistryKey key5 = key4.CreateSubKey("CurrentVersion");             RegistryKey key6 = key5.CreateSubKey("Run");             runs = key6;         }         String[] runsName = runs.GetValueNames();         foreach (String strName in runsName)         {             if (strName.ToUpper() == KeyName.ToUpper())             {                 _exist = true; return _exist;             }         }         return _exist;     }     catch { return false; } } /// /// 写入或删除注册表键值对,即设为开机启动或开机不启动 /// /// 是否开机启动 /// 应用程序名 /// 应用程序路径带程序名 /// private static Boolean SelfRunning(Boolean isStart, String exeName, String path) {     try     {         RegistryKey local = Registry.LocalMachine;         RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);         if (key == null)         {             local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");         }         if (isStart) { key.SetValue(exeName, path); key.Close(); }         else         {             String[] keyNames = key.GetValueNames();             foreach (String keyName in keyNames)             {                 if (keyName.ToUpper() == exeName.ToUpper())                 {                     key.DeleteValue(exeName); key.Close();                 }             }         }     }     catch (Exception ex) { SysLog.Error(ex); return false; }     return true; }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有