對於大多數 Windows 使用者來說,建立捷徑是輕而易舉的基本操作,但對程式開發人員而言,在 .NET 環境下要為應用程式自動建立捷徑卻並非直觀簡單。.NET Framework 本身並未提供直接建立 .lnk 檔案的內建方法,這時我們可以借助 Windows Script Host (WSH) 來達成目標。
捷徑本質上是一個副檔名為 .lnk 的特殊檔案。當你右鍵點選捷徑並選擇「內容」切換到「捷徑」分頁時,可以看到一個捷徑包含以下核心資料:
在 Visual Studio 專案中,右鍵點選專案選擇「加入參考」,切換到 COM 分頁,勾選 Windows Script Host Object Model。這會引入 IWshRuntimeLibrary 命名空間,提供建立捷徑所需的介面。
以下完整範例示範如何在桌面建立指向目前執行組件的捷徑:
using System;
using IWshRuntimeLibrary;
class Program
{
static void Main(string[] args)
{
WshShell shell = new WshShell();
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string shortcutPath = System.IO.Path.Combine(desktopPath, "My Application.lnk");
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
shortcut.WorkingDirectory = Environment.CurrentDirectory;
shortcut.WindowStyle = 1; // 1 = 一般視窗
shortcut.Description = "Launch My Application";
// 使用系統 shell32.dll 中的第 165 個圖示
shortcut.IconLocation = Path.Combine(Environment.SystemDirectory, "shell32.dll") + ", 165";
shortcut.Save();
}
}
Assembly.GetExecutingAssembly().Location 取得目前程式位置。Environment.CurrentDirectory。透過 WSH,我們能在 C# 中靈活建立、修改捷徑,滿足安裝程式、自動部署等實際開發需求。