核心代码
using System; using System.IO; using System.Runtime.InteropServices; using IWshRuntimeLibrary; // 需要添加对IWshRuntimeLibrary的引用 在nuget里面安装Interop.IWshRuntimeLibrary namespace DesktopShortcutCreator { class Program { static void Main(string[] args) { try { // 检查桌面上是否已存在快捷方式 string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string shortcutPath = Path.Combine(desktopPath, "应用程序名称.lnk"); if (!File.Exists(shortcutPath)) { // 创建快捷方式 CreateShortcut(shortcutPath); Console.WriteLine("已在桌面创建快捷方式"); } else { Console.WriteLine("桌面快捷方式已存在"); } // 继续执行应用程序的其他逻辑 Console.WriteLine("应用程序正在运行..."); // 这里可以添加你的应用程序主逻辑 Console.ReadLine(); } catch (Exception ex) { Console.WriteLine($"创建快捷方式时出错: {ex.Message}"); } } static void CreateShortcut(string shortcutPath) { // 获取当前应用程序的可执行文件路径 string targetPath = System.Reflection.Assembly.GetExecutingAssembly().Location; // 创建WshShell对象 WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath); // 设置快捷方式属性 shortcut.TargetPath = targetPath; shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); shortcut.Description = "应用程序描述"; shortcut.IconLocation = targetPath + ",0"; // 使用应用程序自身的图标 // 保存快捷方式 shortcut.Save(); } } }
本文来自 www.luofenming.com