前言
之前一篇文章写了windows程序自启动的方式一,修改注册表,详细信息见C#实现应用程序自启动的几种方法(winform为例)。这盘文章介绍另外一个方法将需要自动启动的应用程序的快捷方式放到windows自启动目录下面。在测试过程中,楼主发现大名鼎鼎的截图软件按snipaste就是采用这种方式来实现自启动的
自启动目录一般是: 和用户名有关
C:\Users\ping\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
一、使用步骤
1.引入库
引用->添加引用->点到COM->搜索Windows Script Host Object Model->确定
2. 在checkedbox的change事件中编写流程
/// <summary>
/// 快捷方式名称-任意自定义
/// </summary>
private const string QuickName = "TestApp";
//private string systemAutoStartPath;
/// <summary>
/// 获取系统自动启动目录
/// </summary>
public string SystemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }
/// <summary>
/// 获取程序完整路径
/// </summary>
public string AppAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }
/// <summary>
/// 自动获取桌面目录
/// </summary>
public string DesktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }
private void ckbAutoLaunch_CheckedChanged(object sender, EventArgs e)
{
if(ckbAutoLaunch.Checked)
{
// 获取启动路径应用程序快捷方式的路径集合
List<string> shortcutPaths = GetQuickFromFolder(this.SystemStartPath, this.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++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//创建桌面快捷方式-如果需要可以取消注释
//CreateDesktopQuick(desktopPath, QuickName, appAllPath);
// 将checkbox的勾选结果持久化到json文件中
WriteJson("IsAutoLaunch", ckbAutoLaunch.Checked);
}
3.编写其他方法
/// <summary>
/// 获取指定文件夹下指定应用程序的快捷方式路径集合
/// </summary>
/// <param name="systemStartPath">文件夹</param>
/// <param name="appAllPath">目标应用程序路径</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private List<string> GetQuickFromFolder(string directory, string targetPath)
{
List<string> tempStrs = new List<string>();
tempStrs.Clear();
string tempStr = null;
string[] files = Directory.GetFiles(directory, "*.lnk");
if(files == null || files.Length == 0)
{
return tempStrs;
}
for (int i = 0; i < files.Length; i++)
{
tempStr = GetAppPathFromQuick(files[i]);
if(tempStr == targetPath)
{
tempStrs.Add(files[i]);
}
}
return tempStrs;
}
/// <summary>
/// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private string GetAppPathFromQuick(string shortcutPath)
{
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
return shortct.TargetPath;
}
else
{
return "";
}
}
/// <summary>
/// 向目标路径创建指定文件的快捷方式
/// </summary>
/// <param name="directory">目标目录</param>
/// <param name="shortcutName">快捷方式名字</param>
/// <param name="targetPath">文件完全路径</param>
/// <param name="description">描述</param>
/// <param name="iconLocation">图标地址</param>
/// <returns>成功或失败</returns>
private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
try
{
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); //目录不存在则创建
//添加引用 Com 中搜索 Windows Script Host Object Model
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); //合成路径
WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath); //创建快捷方式对象
shortcut.TargetPath = targetPath; //指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //设置起始位置
shortcut.WindowStyle = 1; //设置运行方式,默认为常规窗口
shortcut.Description = description; //设置备注
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation; //设置图标路径
shortcut.Save(); //保存快捷方式
return true;
}
catch (Exception ex)
{
string temp = ex.Message;
temp = "";
}
return false;
}
/// <summary>
/// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式
/// </summary>
/// <param name="path">路径</param>
private void DeleteFile(string path)
{
FileAttributes attr = System.IO.File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
}
/// <summary>
/// 在桌面上创建快捷方式-如果需要可以调用
/// </summary>
/// <param name="desktopPath">桌面地址</param>
/// <param name="appPath">应用路径</param>
public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
{
List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
//如果没有则创建
if (shortcutPaths.Count < 1)
{
CreateShortcut(desktopPath, quickName, appPath, "软件描述");
}
}
4.完整代码
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IWshRuntimeLibrary;
namespace AutoLaunch_windowsAutoLaunchDirectory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 快捷方式名称-任意自定义
/// </summary>
private const string QuickName = "TestApp";
//private string systemAutoStartPath;
/// <summary>
/// 获取系统自动启动目录
/// </summary>
public string SystemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }
/// <summary>
/// 获取程序完整路径
/// </summary>
public string AppAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }
/// <summary>
/// 自动获取桌面目录
/// </summary>
public string DesktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }
private void Form1_Load(object sender, EventArgs e)
{
ckbAutoLaunch.Checked = ReadJson("IsAutoLaunch");
}
/// <summary>
/// 读取json配置文件,在窗体load事件中给checkbox 的checked属性赋值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private bool ReadJson(string key)
{
// 可以把下面的代码放在try catch 中,并结合日志文件打印输出
string path = Application.StartupPath + @"\Properties\appSettings.json";
//StreamRead 和 StreamWriter 只能读写文本文件,比如txt,log,json... 读取写入非文本文件,比如多媒体文件可以考虑使用FileStream类
using (StreamReader sr = new StreamReader(path))
{
string jsonStr = sr.ReadToEnd();
// 对读到的json字符串进行反序列化
Dictionary<string, object> jsonObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonStr);
//dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr); // 用dynamic作为泛型类或许更好
return (bool)jsonObj[key];
}
}
/// <summary>
/// 写入json,修改后写入
/// </summary>
/// <param name="key"></param>
/// <param name="checked"></param>
private void WriteJson(string key, bool Ischecked)
{
string path = Application.StartupPath + @"\Properties\appSettings.json";
string newJsonStr = "";
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = fs.Read(buffer, 0, buffer.Length);
string jsonStr = Encoding.Default.GetString(buffer, 0, r);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr);
jsonObj[key] = Ischecked;
// 序列化Json对象
newJsonStr = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
/*byte[] newBuffer = Encoding.Default.GetBytes(newJsonStr);
File.Delete(path);
fs.Write(newBuffer, 0, newBuffer.Length);*/
}
System.IO.File.WriteAllText(path, newJsonStr);
}
private void ckbAutoLaunch_CheckedChanged(object sender, EventArgs e)
{
if(ckbAutoLaunch.Checked)
{
// 获取启动路径应用程序快捷方式的路径集合
List<string> shortcutPaths = GetQuickFromFolder(this.SystemStartPath, this.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++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//创建桌面快捷方式-如果需要可以取消注释
//CreateDesktopQuick(desktopPath, QuickName, appAllPath);
// 将checkbox的勾选结果持久化到json文件中
WriteJson("IsAutoLaunch", ckbAutoLaunch.Checked);
}
/// <summary>
/// 获取指定文件夹下指定应用程序的快捷方式路径集合
/// </summary>
/// <param name="systemStartPath">文件夹</param>
/// <param name="appAllPath">目标应用程序路径</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private List<string> GetQuickFromFolder(string directory, string targetPath)
{
List<string> tempStrs = new List<string>();
tempStrs.Clear();
string tempStr = null;
string[] files = Directory.GetFiles(directory, "*.lnk");
if(files == null || files.Length == 0)
{
return tempStrs;
}
for (int i = 0; i < files.Length; i++)
{
tempStr = GetAppPathFromQuick(files[i]);
if(tempStr == targetPath)
{
tempStrs.Add(files[i]);
}
}
return tempStrs;
}
/// <summary>
/// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private string GetAppPathFromQuick(string shortcutPath)
{
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
return shortct.TargetPath;
}
else
{
return "";
}
}
/// <summary>
/// 向目标路径创建指定文件的快捷方式
/// </summary>
/// <param name="directory">目标目录</param>
/// <param name="shortcutName">快捷方式名字</param>
/// <param name="targetPath">文件完全路径</param>
/// <param name="description">描述</param>
/// <param name="iconLocation">图标地址</param>
/// <returns>成功或失败</returns>
private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
try
{
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); //目录不存在则创建
//添加引用 Com 中搜索 Windows Script Host Object Model
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); //合成路径
WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath); //创建快捷方式对象
shortcut.TargetPath = targetPath; //指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //设置起始位置
shortcut.WindowStyle = 1; //设置运行方式,默认为常规窗口
shortcut.Description = description; //设置备注
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation; //设置图标路径
shortcut.Save(); //保存快捷方式
return true;
}
catch (Exception ex)
{
string temp = ex.Message;
temp = "";
}
return false;
}
/// <summary>
/// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式
/// </summary>
/// <param name="path">路径</param>
private void DeleteFile(string path)
{
FileAttributes attr = System.IO.File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
}
/// <summary>
/// 在桌面上创建快捷方式-如果需要可以调用
/// </summary>
/// <param name="desktopPath">桌面地址</param>
/// <param name="appPath">应用路径</param>
public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
{
List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
//如果没有则创建
if (shortcutPaths.Count < 1)
{
CreateShortcut(desktopPath, quickName, appPath, "软件描述");
}
}
}
}
5.参考代码
/// <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++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//创建桌面快捷方式-如果需要可以取消注释
//CreateDesktopQuick(desktopPath, QuickName, appAllPath);
}
/// <summary>
/// 向目标路径创建指定文件的快捷方式
/// </summary>
/// <param name="directory">目标目录</param>
/// <param name="shortcutName">快捷方式名字</param>
/// <param name="targetPath">文件完全路径</param>
/// <param name="description">描述</param>
/// <param name="iconLocation">图标地址</param>
/// <returns>成功或失败</returns>
private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
try
{
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); //目录不存在则创建
//添加引用 Com 中搜索 Windows Script Host Object Model
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); //合成路径
WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath); //创建快捷方式对象
shortcut.TargetPath = targetPath; //指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //设置起始位置
shortcut.WindowStyle = 1; //设置运行方式,默认为常规窗口
shortcut.Description = description; //设置备注
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation; //设置图标路径
shortcut.Save(); //保存快捷方式
return true;
}
catch(Exception ex)
{
string temp = ex.Message;
temp = "";
}
return false;
}
/// <summary>
/// 获取指定文件夹下指定应用程序的快捷方式路径集合
/// </summary>
/// <param name="directory">文件夹</param>
/// <param name="targetPath">目标应用程序路径</param>
/// <returns>目标应用程序的快捷方式</returns>
private List<string> GetQuickFromFolder(string directory, string targetPath)
{
List<string> tempStrs = new List<string>();
tempStrs.Clear();
string tempStr = null;
string[] files = Directory.GetFiles(directory, "*.lnk");
if (files == null || files.Length < 1)
{
return tempStrs;
}
for (int i = 0; i < files.Length; i++)
{
//files[i] = string.Format("{0}\\{1}", directory, files[i]);
tempStr = GetAppPathFromQuick(files[i]);
if (tempStr == targetPath)
{
tempStrs.Add(files[i]);
}
}
return tempStrs;
}
/// <summary>
/// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动
/// </summary>
/// <param name="shortcutPath"></param>
/// <returns></returns>
private string GetAppPathFromQuick(string shortcutPath)
{
//快捷方式文件的路径 = @"d:\Test.lnk";
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
//快捷方式文件指向的路径.Text = 当前快捷方式文件IWshShortcut类.TargetPath;
//快捷方式文件指向的目标目录.Text = 当前快捷方式文件IWshShortcut类.WorkingDirectory;
return shortct.TargetPath;
}
else
{
return "";
}
}
/// <summary>
/// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式
/// </summary>
/// <param name="path">路径</param>
private void DeleteFile(string path)
{
FileAttributes attr = System.IO. File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
}
/// <summary>
/// 在桌面上创建快捷方式-如果需要可以调用
/// </summary>
/// <param name="desktopPath">桌面地址</param>
/// <param name="appPath">应用路径</param>
public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
{
List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
//如果没有则创建
if (shortcutPaths.Count < 1)
{
CreateShortcut(desktopPath, quickName, appPath, "软件描述");
}
}
总结
感觉这种方式挺常用的,snipaste就是这样
最后感谢这篇文章
C#程序实现软件开机自动启动的两种常用方法