首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 使用 WSH (Windows Script Host) 創建快捷方式完整指南

     編輯:關於C#

背景:.NET 無原生快捷方式 API

.NET Framework (含 .NET Core) **不提供直接創建 `.lnk` 快捷方式的托管 API**。標準解決方案:引用 **COM 組件 `Windows Script Host Object Model` (IWshRuntimeLibrary)**,利用 `WshShell` 創建快捷方式。

步驟 1:添加 COM 引用

  1. 專案右鍵 → 添加引用 → COM 選項卡。
  2. 搜索並勾選 Windows Script Host Object Model (通常版本 1.0)。
  3. 確定 → 專案生成 `Interop.IWshRuntimeLibrary.dll` (嵌入互操作類型默認 True)。

步驟 2:核心創建代碼

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}");
    }
}

屬性詳細說明

屬性類型說明示例
TargetPathstring目標文件/可執行程序路徑`@"C:\App\MyApp.exe"`
Argumentsstring啟動參數 (傳遞給 Main(string[] args))`"/config:prod /verbose"`
WorkingDirectorystring進程工作目錄 (相對路徑解析基準)`@"C:\App\Data"`
WindowStyleint窗口顯示狀態`1`=正常, `3`=最大化, `7`=最小化
Descriptionstring懸停提示/屬性頁描述`"生產環境啟動器"`
IconLocationstring圖標文件路徑 + 索引 (格式: `path, index`)`@"C:\App\icon.ico, 0"` 或 `shell32.dll, 165`
Hotkeystring全局熱鍵 (格式: `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...
        }
    }
    // 正常啟動邏輯...
}

避坑指南與最佳實踐

  • ✅ **引用嵌入互操作類型**:專案引用屬性 `Embed Interop Types = True` (默認),部署時無需攜帶 Interop DLL。
  • ✅ **路徑使用 `Path.Combine`**:避免手動拼接 `\` 導致跨平台/空格路徑錯誤。
  • ✅ **熱鍵無空格**:`"CTRL+ALT+F11"` 正確,`"CTRL + ALT + F11"` 失效。
  • ✅ **圖標索引**:`.exe`/.`ico` 通常索引 0;`shell32.dll` 系統圖標庫豐富 (0-300+),可用工具 (如 Resource Hacker) 預覽。
  • ❌ **不要在無 UI 服務/後台線程創建快捷方式**:WSH 依賴 COM 單元執行緒模型 (STA),需 `[STAThread]` 或 UI 線程調用。
  • ❌ **目標路徑不存在時**:`Save()` 不會報錯,但快捷方式無效。建議創建前 `File.Exists(targetPath)` 驗證。
  • 🔧 **現代替代**:.NET Core 3.0+ 可用 Windows Shortcut Interop 純托管庫 (NuGet: `WindowsShortcut`) 避免 COM 依賴。

驗證快捷方式屬性 (讀取)

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}");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved