Winform程序在双击exe启动之后需要在桌面创建快捷方式,并且设置快捷方式的名称图标等。
注:
博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
1、首先新建创建桌面快捷方式工具类ShortCutHelper
using IWshRuntimeLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace DataConvert.dataconvert
{class ShortCutHelper{//int WindowStyle 说明//1 激活并显示窗口。如果该窗口被最小化或最大化,则系统将其还原到初始大小和位置。//3 激活窗口并将其显示为最大化窗口。//7 最小化窗口并激活下一个顶级窗口。/// /// 创建快捷方式/// /// 快捷方式所处的文件夹/// 快捷方式名称/// 目标路径/// 描述/// 图标路径,格式为"可执行文件或DLL路径, 图标编号",/// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"/// public static void CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null){if (!System.IO.Directory.Exists(directory)){Directory.CreateDirectory(directory);}string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));WshShell shell = new WshShell();IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象shortcut.TargetPath = targetPath;//指定目标路径shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口shortcut.Description = description;//设置备注shortcut.IconLocation = string.IsNullOrEmpty(iconLocation) ? targetPath : iconLocation;//设置图标路径 可不赋值,默认是目标图标shortcut.Save();//保存快捷方式}/// /// 创建桌面快捷方式/// /// 快捷方式名称/// 目标路径/// 描述/// 图标路径,格式为"可执行文件或DLL路径, 图标编号"/// public static void CreateShortcutOnDesktop(string shortcutName, string targetPath, string description = null, string iconLocation = null){iconLocation = Application.StartupPath + "\\images\\beidou.ico";string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation);}}
}
注意这里的WshShell需要添加依赖,右击-管理Nuget程序包-COM-Windows Script Host Object Model
另外这里设置图标路径的时候直接在方法中写死,没用方法传递的参数,而且引入的图片资源也不是在
Resources中管理。
这里直接在项目下新建images目录,并将ico图标文件放在该目录下,注意需要ico的图标格式。
然后获取项目启动路径并拼接
iconLocation = Application.StartupPath + "\\images\\beidou.ico";
2、怎么在项目启动时调用
找到Program.cs
/// /// 应用程序的主入口点。/// [STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);//创建桌面快捷方式ShortCutHelper.CreateShortcutOnDesktop("霸道的程序猿", Application.ExecutablePath);Application.Run(new Form1());}
添加的代码主要是
ShortCutHelper.CreateShortcutOnDesktop("霸道的程序猿", Application.ExecutablePath);
第一个参数是指定的快捷方式名称,图标已经在方法中写死。