需加入參考:Windows Script Host Object Model(IWshRuntimeLibrary)。
using IWshRuntimeLibrary;
public static void CreateShortcut(
string targetPath, // 目標執行檔
string shortcutPath, // 捷徑完整路徑(含 .lnk)
string arguments = "", // 命令列參數
string hotkey = "", // 熱鍵,如 "CTRL+ALT+F11"
string iconPath = "", // 圖示檔案
int iconIndex = 0, // 圖示索引
string description = "",// 提示文字
string workDir = "") // 工作目錄
{
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = targetPath;
shortcut.Arguments = arguments;
shortcut.Hotkey = hotkey.Replace(" ", ""); // 熱鍵不可含空白
shortcut.Description = description;
shortcut.WorkingDirectory = string.IsNullOrEmpty(workDir) ? System.IO.Path.GetDirectoryName(targetPath) : workDir;
if (!string.IsNullOrEmpty(iconPath)) shortcut.IconLocation = $"{iconPath}, {iconIndex}";
shortcut.Save();
}
| 屬性 | 用途 | 範例 |
|---|---|---|
| TargetPath | 目標執行檔/文件路徑 | @"C:\App\MyTool.exe" |
| Arguments | 啟動參數 | "/out:log.txt /verbose" |
| Hotkey | 全域熱鍵(無空白) | "CTRL+ALT+F11" |
| WorkingDirectory | 啟動工作目錄 | @"C:\App\Data" |
| Description | 滑鼠懸停提示 | "我的自訂工具" |
| IconLocation | 圖示來源(檔案,索引) | @"C:\Windows\System32\shell32.dll, 165" |
| WindowStyle | 視窗狀態 1=正常 3=最大化 7=最小化 | 1 |
// 想要 CTRL+ALT+F11 直接執行 MyApp /export /format:pdf
CreateShortcut(
targetPath: @"C:\MyApp\MyApp.exe",
shortcutPath: Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\MyApp匯出.lnk",
arguments: "/export /format:pdf",
hotkey: "CTRL+ALT+F11",
description: "一鍵匯出 PDF 報表"
);
static void Main(string[] args)
{
foreach (string arg in args)
Console.WriteLine(arg); // 依序輸出 /export /format:pdf
// 實際解析建議使用 CommandLineParser 等庫
}