通過 WshShell COM 組件,C# 可輕鬆創建 Windows 快捷方式(.lnk),並設置目標路徑、工作目錄、窗口狀態、圖標、熱鍵等屬性。本文系統梳理核心屬性與實戰技巧。
WshShell 實例;CreateShortcut(string path) 獲取 IWshShortcut;Save() 持久化。| 屬性 | 用途 | 示例 |
|---|---|---|
TargetPath | 目標程序/文件完整路徑 | shortcut.TargetPath = Application.ExecutablePath; |
WorkingDirectory | 啟動時的工作目錄 | shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory; |
WindowStyle | 窗口顯示狀態:1=正常, 3=最大化, 7=最小化 | shortcut.WindowStyle = 3; |
Description | 懸停提示/備註 | shortcut.Description = "啟動我的應用"; |
IconLocation | 圖標路徑與索引,格式 path,index | shortcut.IconLocation = @"%SystemRoot%\System32\Shell32.dll, 165"; |
Arguments | 傳遞給目標程序的命令行參數 | shortcut.Arguments = "/out:output.txt /sortby:date /desc"; |
Hotkey | 全局熱鍵(無空格),如 CTRL+ALT+F11 | shortcut.Hotkey = "CTRL+ALT+F11"; |
using System;
using IWshRuntimeLibrary; // 需引用 COM "Windows Script Host Object Model"
public class ShortcutHelper
{
public static void CreateShortcut(string linkPath, string targetPath, string args = "", string hotkey = "", string description = "", string iconPath = "", int iconIndex = 0)
{
var shell = new WshShell();
var shortcut = (IWshShortcut)shell.CreateShortcut(linkPath);
shortcut.TargetPath = targetPath;
shortcut.Arguments = args;
shortcut.Hotkey = hotkey;
shortcut.Description = description;
if (!string.IsNullOrEmpty(iconPath))
shortcut.IconLocation = $"{iconPath}, {iconIndex}";
shortcut.Save();
}
}
// 用法:
// ShortcutHelper.CreateShortcut(
// @"C:\Users\Public\Desktop\MyApp.lnk",
// Application.ExecutablePath,
// "/auto",
// "CTRL+ALT+F11",
// "自動備份工具",
// @"%SystemRoot%\System32\Shell32.dll", 165);
Hotkey 字符串不能包含空格(如 CTRL + ALT + F11 錯誤,正確 CTRL+ALT+F11)。目標程序在 Main(string[] args) 中即可接收 Arguments 指定的參數:
static void Main(string[] args)
{
foreach (var arg in args) Console.WriteLine(arg);
// 輸出:/out:output.txt /sortby:date /desc
}
掌握 IWshShortcut 屬性,即可實現專業級的快捷方式部署體驗:自動創建桌面/開始菜單圖標、綁定熱鍵、預置啟動參數,大幅提升用戶便利性。