【Windows】C#开机启动帮助类及使用方法

帮助类:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using Microsoft.Win32;
  6: using System.Windows.Forms;
  7: using System.IO;
  8: using System.Diagnostics;
  9: 
 10: namespace Subro
 11: {
 12:     public class AutoStart
 13:     {
 14:         public readonly string ApplicationName;
 15:         readonly string regkeyname;
 16:         /// <summary>
 17:         /// Creates an AutoStart object for the current application
 18:         /// </summary>
 19:         public AutoStart()
 20:             : this(Application.ProductName, Application.ExecutablePath)
 21:         {
 22:         }
 23:         public AutoStart(string ApplicationName)
 24:             : this(null, ApplicationName)
 25:         {
 26:         }
 27:         private AutoStart(string KeyName, string ApplicationName)
 28:         {
 29:             this.ApplicationName = ApplicationName;
 30:             FileInfo fi = new FileInfo(ApplicationName);
 31:             if (!fi.Exists)
 32:                 throw new Exception(ApplicationName + "不存在!");
 33:             regkeyname = KeyName == null ? fi.Name : KeyName;
 34:             startupfolderfile =
 35:             Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\"
 36:             + fi.Name.Replace(fi.Extension, ".lnk");
 37:         }
 38:         public AutoStart(string ApplicationName, params string[] CommandLineArguments)
 39:             : this(ApplicationName)
 40:         {
 41:             this.CommandlineParameters = string.Join(" ", CommandLineArguments);
 42:         }
 43:         readonly RegistryKey startkey = GetStartupRegistryDir();
 44:         private string commandlineparams;
 45:         /// <summary>
 46:         /// gets or sets the command line arguments for the application
 47:         /// </summary>
 48:         public string CommandlineParameters
 49:         {
 50:             get { return commandlineparams; }
 51:             set
 52:             {
 53:                 if (value.Trim().Length == 0) value = null;
 54:                 commandlineparams = value;
 55:                 if (EnabledThroughRegistry)
 56:                     SetRegKey();
 57:             }
 58:         }
 59:         /// <summary>
 60:         /// Sets the <see cref="CommandlineParameters"/> property to the commandlines with which
 61:         /// the application was started
 62:         /// </summary>
 63:         public void SetCurrentCommandLine()
 64:         {
 65:             CommandlineParameters = string.Join(" ", Environment.GetCommandLineArgs());
 66:         }
 67:         private void SetRegKey()
 68:         {
 69:             startkey.SetValue(regkeyname, CompleteName);
 70:         }
 71:         /// <summary>
 72:         /// The complete command line name to start the file including arguments
 73:         /// </summary>
 74:         public string CompleteName
 75:         {
 76:             get
 77:             {
 78:                 return ApplicationName +
 79:                 (commandlineparams == null ? null : " " + commandlineparams);
 80:             }
 81:         }
 82:         /// <summary>
 83:         /// If true a registry item exists that starts the for which this class was created.
 84:         /// </summary>
 85:         public bool EnabledThroughRegistry
 86:         {
 87:             get { return startkey.GetValue(regkeyname) != null; }
 88:             set
 89:             {
 90:                 if (value == EnabledThroughRegistry) return;
 91:                 if (value)
 92:                 {
 93:                     SetRegKey();
 94:                 }
 95:                 else
 96:                 {
 97:                     startkey.DeleteValue(regkeyname);
 98:                 }
 99:             }
100:         }
101:         readonly string startupfolderfile;
102:         public bool EnabledThroughStartupMenu
103:         {
104:             get { return File.Exists(startupfolderfile); }
105:             set
106:             {
107:                 if (EnabledThroughStartupMenu == value) return;
108:                 if (value)
109:                     createshortcut();
110:                 else
111:                     File.Delete(startupfolderfile);
112:             }
113:         }
114:         void createshortcut()
115:         {
116:             //Chosen for creating a shortcut with the help of vbscript
117:             //It's an extra liablility, but better than forcing the
118:             //use of a WSH wrapper.
119:             //An alternative can be found here: http://www.msjogren.net/dotnet/eng/samples/dotnet_shelllink.asp
120:             //Looks very interesting, but didn't try it, since it would inflate the
121:             //use of this simple class too much.
122:             //But still it might be a very good thing to use, especially if
123:             //this doesn't work ;-)
124: 
125:             string file = Application.UserAppDataPath + "\\createshortcut.vbs";
126:             try
127:             {
128:                 StreamWriter sw = new StreamWriter(file);
129:                 sw.Write(string.Format(
130:                 @"Set Shell = CreateObject(""WScript.Shell"")
131:                 Set link = Shell.CreateShortcut(""{0}"")
132:                 link.TargetPath = ""{1}""
133:                 link.Description = ""{2}""
134:                 link.Arguments = ""{3}""
135:                 link.WorkingDirectory = ""{4}""
136:                 link.Save"
137:                 , startupfolderfile, ApplicationName, regkeyname, commandlineparams, new FileInfo(ApplicationName).DirectoryName));
138:                 sw.Close();
139:                 Process.Start(file).WaitForExit();
140:             }
141:             catch
142:             {
143:                 throw;
144:             }
145:             finally
146:             {
147:                 try { File.Delete(file); }
148:                 catch { }
149:             }
150:         }
151:         static AutoStart current;
152:         /// <summary>
153:         /// Returns the AutoStart information for the current application.
154:         /// The object is created upon the first call and kept in memory for
155:         /// faster access. The object can be destroyed if wanted with <see cref="ResetCurrent"/>
156:         /// </summary>
157:         public static AutoStart Current
158:         {
159:             get
160:             {
161:                 if (current == null) current = new AutoStart();
162:                 return current;
163:             }
164:         }
165:         /// <summary>
166:         /// Destroys the object created when <see cref="Current"/> was called.
167:         /// <see cref="Current"/> can still be used, but the object will be recreated
168:         /// </summary>
169:         public static void ResetCurrent()
170:         {
171:             current = null;
172:         }
173:         public static RegistryKey GetStartupRegistryDir()
174:         {
175:             return Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
176:         }
177:         public static string[] GetStartupRegistryApplications()
178:         {
179:             RegistryKey r = GetStartupRegistryDir();
180:             //if (r.SubKeyCount == 0) return new string[0];
181:             return r.GetValueNames();
182:         }
183:     }
184: }
使用方法举例:
  1: Subro.AutoStart.Current.EnabledThroughStartupMenu = true;

【原文地址】

http://blogs.vbcity.com/hotdog/archive/2005/12/08/5733.aspx