
/// <summary> /// 添加到开机自动运行 /// </summary> public static void BootToRunAuto() { //获取可执行文件的全部路径 string exeDir = System.Windows.Forms.Application.ExecutablePath; //获取Run键 RegistryKey key1 = Registry.CurrentUser; RegistryKey key2 = key1.CreateSubKey("SOFTWARE"); RegistryKey key3 = key2.CreateSubKey("Microsoft"); RegistryKey key4 = key3.CreateSubKey("Windows"); RegistryKey key5 = key4.CreateSubKey("CurrentVersion"); RegistryKey key6 = key5.CreateSubKey("Run"); //在Run键中写入一个新的键值 if (key6.GetValue("PrintERP") == null || key6.GetValue("PrintERP").ToString()!="false") key6.SetValue("PrintERP", exeDir); } /// <summary> /// 取消添加开机自动运行 /// </summary> public static void CancleBootRunAuto() { //获取可执行文件的全部路径 string exeDir = System.Windows.Forms.Application.ExecutablePath; //获取Run键 RegistryKey key1 = Registry.CurrentUser; RegistryKey key2 = key1.CreateSubKey("SOFTWARE"); RegistryKey key3 = key2.CreateSubKey("Microsoft"); RegistryKey key4 = key3.CreateSubKey("Windows"); RegistryKey key5 = key4.CreateSubKey("CurrentVersion"); RegistryKey key6 = key5.CreateSubKey("Run"); if (CheckKeyExists(key6, "PrintERP")) { //取消自启动 key6.SetValue("PrintERP", false); } } /// <summary> /// 检查注册表项是否存在 /// </summary> public static bool CheckKeyExists(RegistryKey key, string keyName) { bool isexists = false; foreach (string keyname in key.GetValueNames()) { if (keyname.Equals(keyName)) { isexists = true; break; } } return isexists; }
如果你是管理员权限,那么你可以考虑修改注册表来达到这个功能,当然你也可以把修改注册表提前告诉用户,毕竟有的用户不喜欢随便修改自己的东西。
那修改的路径就在这个地方:
readonly
string
regPath =
@"SoftwareMicrosoftWindowsCurrentVersionRun"
;
然后,你要获得你的程序的路径,可以:Application.ExecutablePath,或者 Environment.CurrentDirectory + "\XX.exe"。然后就是修改注册表了。
RegistryKey rk = Registry.LocalMachine; RegistryKey key = rk.CreateSubKey(regPath); key.SetValue("XX", appPath); rk.Close();
先要打开主KEY,在HKEY_LOCAL_MACHINE。第一行代码可以看出。
然后在这个修改自启动的路径下创建一个KEY,然后设置一个值,SetValue 第一个参数,是你这个键值的名字,可以随便起,然后是你的程序的路径。
OK,最后CLOSE 掉。
你也可以try 一下 这段代码,然后 catch 这个异常:UnauthorizedAccessException 。顾名思义,你可以弹出个窗体,警告用户:你没有相应权限。
当你没有管理权限,也就是不能修改注册表时,你可以考虑另一种方法。
那就是创建你的快捷方式,也就是创建一个.lnk 的文件。
首先你需要添加引用,选择 COM 选项卡,然后 选择Windows Script Host Object Model。然后写上
using
IWshRuntimeLibrary;
WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Startup)+ " " + "\XX.lnk"); shortcut.TargetPath = Application.ExecutablePath; shortcut.WorkingDirectory = System.Environment.CurrentDirectory; shortcut.WindowStyle = 1; shortcut.Description = "XX Application"; shortcut.Save();
先是创建 Shortcut ,在 Startup 这个目录下。
然后制定一系列的属性值。
TargetPath 设置你的程序的位置。
WorkingDirectory 工作目录。
WindowStyle :1、为 normal ,3、Maximized,7、Minimized。
Description:描述。
最后一定要Save,否则只 CcreateShortcut 是创建不出 快捷方式的。
(转载自:http://www.soaspx.com/dotnet/csharp/csharp_20110820_7980.html)