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

C# 建立捷徑完整指南:WshShell COM 介面、熱鍵、命令列參數與啟動目錄

     編輯:關於C#

核心 COM 物件

需加入參考: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 等庫
}

注意事項

  • 需在目標機器安裝 Windows Script Host(Windows 內建)。
  • 熱鍵註冊為全域,若衝突會失效;建議提供 UI 讓使用者自訂。
  • 捷徑檔實為二進位格式,不可直接用文字編輯器修改。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved