Winform中实现程序初始化时在桌面创建快捷方式并设置图标(获取ico图片资源路径)
创始人
2025-05-29 11:29:01

场景

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);

第一个参数是指定的快捷方式名称,图标已经在方法中写死。

相关内容

热门资讯

印尼,大事发生! 来 源:正和岛(ID:zhenghedao)12月1日-5日,“全球共生·协作共赢——2025中印尼...
2025摩托车1-11月销量:... 燃油摩托销量有多大?我国进入电动摩托车时代了吗?受新能源的冲击大吗?事实上,答案是否定的,冲击也不大...
【开盘】A股三大股指开盘涨跌互... 12月17日,A股三大股指开盘涨跌互现。其中,沪指跌0.06%报382.51点,深成指涨0.1%报1...
麦当劳再涨价!网友大呼“还我穷... 12月15日,麦当劳中国正式对多款核心餐品启动价格调整,涨幅集中在0.5元至1元区间,“麦当劳涨价”...
朗信电气:关联方贡献超10亿元... 《金证研》北方资本中心 亦戈/作者 廉贞 映蔚/风控2025年12月13日,江苏朗信电气股份有限公司...