自动创建快捷方式
2021-05-11 本文已影响0人
RICK_216
#region 快捷方式
/// <summary>
/// 为当前应用创建快捷方式
/// </summary>
public static void CreateCurrentShortcutOnDesktop()
{
// 获取当前应用程序目录地址
string targetPath = Process.GetCurrentProcess().MainModule.FileName;
string workingDirectory = Environment.CurrentDirectory;
CreateShortcutOnDesktop(targetPath, workingDirectory, "快捷方式");
}
/// <summary>
/// 创建快捷方式到桌面
/// </summary>
/// <param name="targetPath"></param>
/// <param name="workingDirectory"></param>
/// <param name="shortcutName"></param>
public static void CreateShortcutOnDesktop(string targetPath, string workingDirectory, string shortcutName)
{
string stopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
CreatShortcut(targetPath, workingDirectory, shortcutName, stopPath);
}
/// <summary>
/// 创建开机启动方式到启动文件夹
/// </summary>
/// <param name="targetPath"></param>
/// <param name="workingDirectory"></param>
/// <param name="shortcutName"></param>
public static void CreateShortcutOnStartup(string targetPath, string workingDirectory, string shortcutName)
{
//若只为当前用户创建:用Environment.SpecialFolder.Startup
string stopPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup);
CreatShortcut(targetPath, workingDirectory, shortcutName, stopPath);
}
/// <summary>
/// 创建快捷方式
/// </summary>
/// <param name="targetPath">目标</param>
/// <param name="workingDirectory">起始位置</param>
/// <param name="shortcutName">快捷方式名称</param>
/// <param name="stopPath">创建位置</param>
private static void CreatShortcut(string targetPath, string workingDirectory, string shortcutName, string stopPath)
{
//添加引用 (com->Windows Script Host Object Model),using IWshRuntimeLibrary;
string shortcutPath = Path.Combine(stopPath, $"{shortcutName}.lnk");
if (!System.IO.File.Exists(shortcutPath))
{
IWshShell shell = new WshShell();
// 确定是否已经创建的快捷键被改名了
foreach (var item in Directory.GetFiles(stopPath, "*.lnk"))
{
WshShortcut tempShortcut = (WshShortcut)shell.CreateShortcut(item);
if (tempShortcut.TargetPath == targetPath)
{
return;
}
}
WshShortcut shortcut = (WshShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = targetPath;// 目标路径
shortcut.Arguments = "";// 参数
shortcut.Description = "应用程序说明";
shortcut.WorkingDirectory = workingDirectory;
shortcut.IconLocation = System.Environment.SystemDirectory + "" + "shell32.dll, 165";//图标,该图标是应用程序的资源文件
//shortcut.IconLocation = targetPath;//图标,该图标是应用程序的资源文件
//shortcut.Hotkey = "CTRL+SHIFT+W";//热键,发现没作用,大概需要注册一下
shortcut.WindowStyle = 1;
shortcut.Save();
}
}
#endregion