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

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

相关内容

热门资讯

“要带更多商业合作”来中国 随着斯塔默访华及中英新一轮高层对话,两国经贸关系呈现“暖春”态势。“将加快塑造吸引外资的新优势,让外...
2026年了,高速充电还难么?... 2月17日,正月初一,天刚蒙蒙亮,上海的街头还浸在除夕夜的余温里。红灯笼挂满了小区楼道,这是一年中最...
太空制药--商业航天的“新场景... 太空经济过去十几年最像两门生意:把东西送上去(火箭与基础设施),以及在天上把信号卖回来(卫星通信)。...
春节后资金面前瞻:首周超2.2... 春节前央行通过逆回购、买断式逆回购等多种公开市场工具加大资金投放,呵护流动性保持宽松。面对节后大量逆...
公募密集调研,机构:春晚对人形... 来源:环球网【环球网财经综合报道】今年春晚,机器人相关话题热度居高不下。节前,多家相关企业已成为公募...