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

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

相关内容

热门资讯

玩家攻略「陕西三带」为什么一直... 您好:陕西三带这款游戏可以开挂,确实是有挂的,需要了解加客服微信【9183893】很多玩家在这款游戏...
实测分享“朋友圈其实真有透视挂... 您好:朋友圈这款游戏可以开挂,确实是有挂的,需要软件加微信【4194432】,很多玩家在朋友圈这款游...
玩家实测“微乐湖南麻将其实有挂... 您好:微乐湖南麻将这款游戏可以开挂,确实是有挂的,需要软件加微信【8700483】,很多玩家在微乐湖...
今日重大通报“新永和确实可以开... 亲:新永和这款游戏是可以开挂的,确实是有挂的,添加客服【3671900】很多玩家在这款游戏中怀疑是不...
最新消息“新荣耀究竟有挂吗.”... 您好:【新荣耀】这款游戏可以开挂,确实是有挂的,需要了解加客服微信【6670747】很多玩家在这款游...