C#/WPF/WinForm/.NET程序代码实现软件程序开机自动启动的两种常用方法函数的示例与实例带详细注释
方法一:将软件的快捷方式创建到计算机的自动启动目录下(不需要管理员权限)
1.必要引用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using IWshRuntimeLibrary; using System.Diagnostics;
2.代码实现-只需要调用SetMeAutoStart(bool onOff)方法就可以了,参数onOff表示自启开关
/// <summary> /// 快捷方式名称-任意自定义 /// </summary> private const string QuickName = "TCNVMClient"; /// <summary> /// 自动获取系统自动启动目录 /// </summary> private string systemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } } /// <summary> /// 自动获取程序完整路径 /// </summary> private string appAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } } /// <summary> /// 自动获取桌面目录 /// </summary> private string desktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } } /// <summary> /// 设置开机自动启动-只需要调用改方法就可以了参数里面的bool变量是控制开机启动的开关的,默认为开启自启启动 /// </summary> /// <param name="onOff">自启开关</param> public void SetMeAutoStart(bool onOff = true) { if (onOff)//开机启动 { //获取启动路径应用程序快捷方式的路径集合 List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath); //存在2个以快捷方式则保留一个快捷方式-避免重复多于 if (shortcutPaths.Count >= 2) { for (int i = 1; i < shortcutPaths.Count; i++) { DeleteFile(shortcutPaths[i]); } } else if (shortcutPaths.Count < 1)//不存在则创建快捷方式 { CreateShortcut(systemStartPath, QuickName, appAllPath, "中吉售货机"); } } else//开机不启动 { //获取启动路径应用程序快捷方式的路径集合 List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath); //存在快捷方式则遍历全部删除 if (shortcutPaths.Count > 0) { for (int i = 0; i < shortcutPaths.Count; i+