.NET Framework (含 .NET Core) **不提供直接創建 `.lnk` 快捷方式的托管 API**。標準解決方案:引用 **COM 組件 `Windows Script Host Object Model` (IWshRuntimeLibrary)**,利用 `WshShell` 創建快捷方式。
using System;
using System.Reflection;
using IWshRuntimeLibrary;
class Program {
static void Main() {
// 1. 創建 WshShell 實例
var shell = new WshShell();
// 2. 確定快捷方式完整路徑 (桌面 + 文件名)
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string shortcutPath = System.IO.Path.Combine(desktop, "MyApp.lnk");
// 3. 創建 IWshShortcut 實例 (此時僅內存對象,未寫入磁盤)
var shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
// 4. 設置屬性
shortcut.TargetPath = Assembly.GetExecutingAssembly().Location; // 指向當前程序
shortcut.WorkingDirectory = Environment.CurrentDirectory; // 工作目錄
shortcut.WindowStyle = 1; // 1=正常, 3=最大化, 7=最小化
shortcut.Description = "啟動我的應用程序";
shortcut.IconLocation = System.IO.Path.Combine(
Environment.SystemDirectory, "shell32.dll") + ", 165"; // 系統圖標索引
// 5. 可選:命令行參數與熱鍵
shortcut.Arguments = "/out:output.txt /sortby:date /desc";
shortcut.Hotkey = "CTRL+ALT+F11"; // 無空格!
// 6. 保存到磁盤 (關鍵步驟!)
shortcut.Save();
Console.WriteLine($"快捷方式已創建: {shortcutPath}");
}
}
| 屬性 | 類型 | 說明 | 示例 |
|---|---|---|---|
| TargetPath | string | 目標文件/可執行程序路徑 | `@"C:\App\MyApp.exe"` |
| Arguments | string | 啟動參數 (傳遞給 Main(string[] args)) | `"/config:prod /verbose"` |
| WorkingDirectory | string | 進程工作目錄 (相對路徑解析基準) | `@"C:\App\Data"` |
| WindowStyle | int | 窗口顯示狀態 | `1`=正常, `3`=最大化, `7`=最小化 |
| Description | string | 懸停提示/屬性頁描述 | `"生產環境啟動器"` |
| IconLocation | string | 圖標文件路徑 + 索引 (格式: `path, index`) | `@"C:\App\icon.ico, 0"` 或 `shell32.dll, 165` |
| Hotkey | string | 全局熱鍵 (格式: `CTRL+ALT+KEY`,**不可含空格**) | `"CTRL+SHIFT+F12"` |
public static void CreateStartupShortcut(string appPath, string shortcutName, string arguments = "") {
var shell = new WshShell();
// 啟動文件夾: shell:startup
string startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string path = System.IO.Path.Combine(startup, shortcutName + ".lnk");
var shortcut = (IWshShortcut)shell.CreateShortcut(path);
shortcut.TargetPath = appPath;
shortcut.Arguments = arguments;
shortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(appPath);
shortcut.Description = "開機自啟動";
shortcut.Save();
}
// Program.cs
static void Main(string[] args) {
foreach (var arg in args) {
Console.WriteLine($"參數: {arg}");
// 解析邏輯: /out:xxx → key=out, value=xxx
if (arg.StartsWith("/")) {
var parts = arg.Substring(1).Split(new[] { ':' }, 2);
string key = parts[0].ToLower();
string value = parts.Length > 1 ? parts[1] : "";
// 處理 key/value...
}
}
// 正常啟動邏輯...
}
var shell = new WshShell();
var shortcut = (IWshShortcut)shell.CreateShortcut(@"C:\Path\To\Shortcut.lnk");
Console.WriteLine($"目標: {shortcut.TargetPath}");
Console.WriteLine($"參數: {shortcut.Arguments}");
Console.WriteLine($"工作目錄: {shortcut.WorkingDirectory}");
Console.WriteLine($"熱鍵: {shortcut.Hotkey}");