首页 > 代码库 > C#设置某程序开机自启动[修改注册表方式]
C#设置某程序开机自启动[修改注册表方式]
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using Microsoft.Win32; 7 using org.nipc.securityManager.client.UpdateModule; 8 9 namespace SettingAutoRun 10 { 11 class Program 12 { 13 //static void Main(string[] args) 14 //{ 15 // string outStr = TryGetSoftwarePath("DTLite"); 16 // bool a = SetAutoRun("DTLite", outStr); 17 // Console.WriteLine(a); 18 // Console.ReadKey(); 19 20 //} 21 22 public static bool SetAutoRun(string keyName, string filePath) 23 { 24 25 try 26 { 27 28 RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); 29 runKey.SetValue(keyName, filePath); 30 runKey.Close(); 31 32 } 33 34 catch 35 { 36 37 return false; 38 39 } 40 41 return true; 42 43 } 44 45 public static bool DeleteAutoRun(string keyName) 46 { 47 48 try 49 { 50 51 RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); 52 53 runKey.DeleteValue(keyName); 54 55 runKey.Close(); 56 57 } 58 59 catch 60 { 61 62 return false; 63 64 } 65 66 return true; 67 68 } 69 70 public static string TryGetSoftwarePath(string softName) 71 { 72 string path = ""; 73 string strPathResult = string.Empty; 74 string strKeyName = ""; //"(Default)" key, which contains the intalled path 75 object objResult = null; 76 77 Microsoft.Win32.RegistryValueKind regValueKind; 78 Microsoft.Win32.RegistryKey regKey = null; 79 Microsoft.Win32.RegistryKey regSubKey = null; 80 81 try 82 { 83 //Read the key 84 regKey = Microsoft.Win32.Registry.LocalMachine; 85 regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" + softName.ToString() + ".exe", false); 86 87 //Read the path 88 objResult = regSubKey.GetValue(strKeyName); 89 regValueKind = regSubKey.GetValueKind(strKeyName); 90 91 //Set the path 92 if (regValueKind == Microsoft.Win32.RegistryValueKind.String) 93 { 94 strPathResult = objResult.ToString(); 95 } 96 } 97 catch (System.Security.SecurityException ex) 98 { 99 throw new System.Security.SecurityException("You have no right to read the registry!", ex);100 }101 catch (Exception ex)102 {103 throw new Exception("Reading registry error!", ex);104 }105 finally106 {107 108 if (regKey != null)109 {110 regKey.Close();111 regKey = null;112 }113 114 if (regSubKey != null)115 {116 regSubKey.Close();117 regSubKey = null;118 }119 }120 121 if (strPathResult != string.Empty)122 {123 //Found 124 path = strPathResult;125 return path;126 }127 else128 {129 //Not found 130 path = null;131 return path;132 }133 } 134 135 136 137 }138 }
C#设置某程序开机自启动[修改注册表方式]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。